Protocol Extensions
Gustavo Barcena, JibJab Bros Studios
What is a Protocol Extension?
What is a Protocol?
A required list of properties and behaviors that can be adopted by classes, structs and even enums
1
What is an Extension?
A construct giving us the ability to add functionality to existing classes, structs and enums. We can also do retroactive modeling where we add functionality to code that we do not have original source.
2
What is a Protocol Extension?
A construct giving us the ability to add functionality to existing protocols.
The Apple Definition
Protocols can be extended to provide method and property implementations to conforming types. This allows you to define behavior on protocols themselves, rather than in each type’s individual conformance or in a global function.
Default Implementation
A protocol extension can be used to add default functionality to a protocol but if something is conforming to the protocol and it implements the method then that functionality is used instead.
Where?
When your define a protocol extension, you can add the "where" clause to only add the functionality to classes that conform to certain rules.
An example of this is applying a precedes function only to items that implement a Comparable protocol.

From WWDC Video

From WWDC Video
Why?
- We can add functionality to existing protocols while keeping our code DRY
- Especially if we can use other methods in the protocol
- This eliminates the need for some global generic functions
- Hard to discover
- Have an awkward syntax

http://www.raywenderlich.com/108522/whats-new-in-swift-2
Food for thought
What if we combined protocol extensions with protocol inheritance
Protocol Oriented Programming
Outside the scope of this talk
Resources
-
http://sketchytech.blogspot.com/2015/06/living-in-post-oop-world-protocols-rule.html
- Talks about switch away from global generics to protocol extensions
-
http://nshipster.com/swift-default-protocol-implementations/
- Talks about limitations with the old systems
-
http://www.swift-studies.com/blog/2015/6/15/exploring-swift-2-protocol-extensions
- Random generators on collections types
-
https://www.reddit.com/r/swift/comments/39o16p/protocol_extensions_in_20/
- Good Overview,
- "When you organise things by protocol, you organise them by what they're able to do, not what they are. And protocol extensions lets you do this in a way you couldn't before."
-
Apple Swift Book
- Definitions, A look at protocol extensions
-
http://www.raywenderlich.com/108522/whats-new-in-swift-2
Questions?
Protocol Extensions
By Gustavo Barcena
Protocol Extensions
- 704