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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With