December 2018
Intermediate to advanced
414 pages
10h 19m
English
Conditional conformance is a feature that lets you provide conformance or extensions to existing types on the condition that a set of requirements is fulfilled.
Let's define a simple protocol:
protocol Summable { var sum: Int { get }}
The previous protocol defines that any type that is Summable should expose a sum property of the Int type.
We can retrofit this type on Arrays of Int types as we know how to add integers together to produce a sum:
extension Array: Summable where Element == Int { var sum: Int { return self.reduce(0) { $0 + $1 } }}[1,2,3,4].sum == 10
It's all good, but now we also want to make sums of all number types. In Swift, there is a base protocol, called Numeric, that is shared by all number types. ...
Read now
Unlock full access