saad_nad
saad_nad

Reputation: 163

Usage of Extensions for implementing delegate functions in Swift

I know that Objective-C categories are called extension in Swift.

But recently i bumped in to this :

extension MyClass : GMSMapViewDelegate
{
    func mapView(mapView: GMSMapView, idleAtCameraPosition position: GMSCameraPosition) 
    {
        print("idleAtCameraPosition")
        self.getAddressFromLocation(mapView.camera.target)
    }

}

This looked like they are implementing delegate functions.This seemed a very good and clean way of implementing delegate functions. So I personally tried it and this works but I think I may be wrong because categories i.e. extensions are not supposed to do this.They were used to add extra functionality to other classes with out subclassing.

So my question is can we use extensions for such purpose or not? If we can do this then extensions are more than just categories.Because i don't think we could achieve this by categories in Objective-C.

Thanks

Upvotes: 7

Views: 4321

Answers (3)

Jonathan H.
Jonathan H.

Reputation: 949

From the official Swift Language Reference:

Extensions in Swift can:

  • Add computed instance properties and computed type properties
  • Define instance methods and type methods
  • Provide new initializers
  • Define subscripts
  • Define and use new nested types
  • Make an existing type conform to a protocol

Yes, extensions are a valid method to make a class conform to a delegate protocol. Not only are extensions valid for this purpose, but they allow for better code organization and follow good style practice in Swift.

Upvotes: 10

Duncan C
Duncan C

Reputation: 131418

Yes you can, and should, do that. Putting the methods that implement a protocol into a class extension is considered good style in Swift. It separates out groups of methods based on what they do. I would suggest making liberal use of extensions in your coding.

Upvotes: 4

Jeremy Gurr
Jeremy Gurr

Reputation: 1623

Yes, extensions are meant to be able to allow existing classes to conform to new protocols, in addition to just adding functions to a class.

Upvotes: 3

Related Questions