Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 290
saad_nad Avatar asked Dec 14 '22 01:12

saad_nad


1 Answers

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.

like image 99
Jonathan H. Avatar answered May 07 '23 06:05

Jonathan H.