Bilue / swift-style-guide

Style guide & coding conventions for Swift projects
Creative Commons Zero v1.0 Universal
14 stars 3 forks source link

Using extensions for protocol/delegate conformance #10

Open dannolan opened 8 years ago

dannolan commented 8 years ago

This is another kind of idiomatic Swift trick that again allows you to decouple certain implementations from your existing structures or classes. The best example is you might have a common view controller that you decide to add a map view to, but you only want to add annotations. Rather than having your class conform to the protocol, have an extension on your class conform

So rather than


class MyCoolViewController : UIViewController, MKMapViewDelegate
{
//my cool class goes here
}

We do the following definition


//regular class
class MyCoolViewController : UIViewController
{
 //my wicked sick class goes here
}

extension MyCoolViewController : MKMapViewDelegate
{
  //delegate conformance goes here
}

What you end up getting from this is a) separation of concerns, but b) locality of concerns, it's also a great way to extend and adapt a particular class if you're getting to code smell lengths of fat view controllers and need to add functionality (or want to expand existing Obj-C view controllers but want to use swell as heck Swift for building upon your existing apps)

rhysforyou commented 8 years ago

Definitely agree with this, doubly so if you ensure those extensions only consume public API so they're acting as a thin wrapper rather than something with a ton of embedded domain logic.

sboddeus commented 8 years ago

Seconded. :+1:

edwardaux commented 8 years ago

Totally agree. One of my personal faves.