6

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

saad_nad
  • 153
  • 2
  • 10

3 Answers3

9

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.

Jonathan H.
  • 939
  • 1
  • 7
  • 21
4

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.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
3

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.

Jeremy Gurr
  • 1,613
  • 8
  • 11
  • 1
    It is important to note that extensions also allow for extended implementation other than conforming to protocols and 'just adding functions to a class' (most notably defining computed instance properties) – Jonathan H. Dec 15 '16 at 18:12