Advanced Swift: A Curious Case of Protocols
Andrew Chub
Senior iOS Developer | Swift | UIKit | SwiftUI | AR Enthusiast | 9+ years of experience
I have never met this question but it is interesting to know.
With Swift protocols we can make:
typealias Codable = Encodable & Decodable
protocol Codable: Encodable, Decodable { }
Sure, in Swift, Codable is a typealias=)
Protocol Composition vs. Protocol Inheritance: What’s the difference, and why is Codable a typealias? Take a moment to think, and then read the explanation from the Advanced Swift 5 book.
Both protocol inheritance and protocol composition have their use cases. For example,
the Comparable protocol inherits from Equatable. This means it can add definitions
such as >= and <= while only requiring conforming types to implement <. In the case of
Codable, it would not have made sense to let Encodable inherit from Decodable or the
other way around. However, it would have made sense to define a new protocol named
Codable that inherits from both Encodable and Decodable. In fact, writing
typealias Codable = Encodable & Decodable is semantically equivalent to writing
protocol Codable: Encodable, Decodable {}. The type alias is a little more lightweight and
makes it clear that Codable is only the composition of the two protocols and doesn’t add
any functionality of its own.