Advanced Swift: A Curious Case of Protocols

Advanced Swift: A Curious Case of Protocols

I have never met this question but it is interesting to know.

With Swift protocols we can make:

  • Protocol Composition

typealias Codable = Encodable & Decodable        

  • Protocol Inheritance

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.







要查看或添加评论,请登录

Andrew Chub的更多文章

  • Basic Fastlane Templates

    Basic Fastlane Templates

    I’ve created a basic template with simple lanes that can serve as a starting point for your own projects. While these…

  • Installing Tuist with Mise

    Installing Tuist with Mise

    If you want to install Tuist, I recommend using Mise. It's a simple and convenient way to install Tuist without…

  • Feature Flags

    Feature Flags

    I never thought I’d write an article about feature flags, but it turns out the topic is quite relevant. This article…

    1 条评论

社区洞察

其他会员也浏览了