NEW: Master Swift design patterns with my latest book! >>

What is protocol-oriented programming?

Written by Paul Hudson    @twostraws

One powerful feature of Swift is its ability to extend protocols – to be able to add new functionality not only to one type, but to a whole collection of types that all conform to the same protocol.

Protocol-oriented programming takes that feature and encourages you to craft your app’s architecture around it so that the first thing you do is sketch out one or more protocols rather than get straight into concrete types.

If you’re coming from a more traditional object-oriented system where inheritance is more common, try to think as your first protocol as being a base class. You can then create new protocols by inheriting from that initial protocol, and write extensions so they have default implementations.

By writing lots of small protocols with extensions, you’re getting a similar approach to multiple inheritance. However, because protocol extensions can’t include state you don’t get any of the cruft, and Swift’s constraint-based conflict resolution is easy enough for everyone to understand.

Available from iOS 9.0 – learn more in my book Pro Swift

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Learn Server-Side Swift now!

Take your Swift code to the server and become a full-stack developer with my latest book: Server-Side Swift!

Click here to visit the Hacking with Swift store >>