Chapter 16: Protocols

大綱

Protocol syntax

  • A protocol can be adopted by a class, struct or enum

    • Once a type implements all members of a protocol, the type is said to conform to the protocol.

Methods in protocols

  • You don’t, and in fact can’t, define any implementation for the methods

  • methods defined in protocols can’t contain default parameters

Properties in protocols

  • you must explicitly mark them as get or get set, somewhat similar to the way you declare computed properties”

Initializers in protocols

  • If you conform to a protocol with required initializers using a class type, those initializers must use the required keyword:

Protocol inheritance

  • you can have protocols that inherit from other protocols, much like you can have classes that inherit from other classes

Implementing properties

  • implementing a get requirement are:

    • A constant stored property.

    • A variable stored property.

    • A read-only computed property.

    • A read-write computed property.

  • Your choices for implementing both a get and a set property are limited to a variable stored property or a read-write computed property

Associated types in protocols

Implementing multiple protocols

  • A class can only inherit from a single class — this is the property of “single inheritance”. In contrast, a class can adopt as many protocols as you’d like!”

Protocol composition

  • 這招很好用, 可以將不同protocol的內容組合再一起。

Extensions and protocol conformance

  • Extensions可以擴充任何type, 即使是standard library. Ex String.

  • Extensions可以讓我們將protocol進行分群。

Requiring reference semantics

  • 不同性質的type實作的protocol, 也具有不同semantics

  • If you have an instance of a class or struct assigned to a variable of a protocol type, it will express value or reference semantics that match the type it was defined as.

Protocols: More than bags of syntax

Equatable

  • 如何實作custom type的Equatable

Comparable

  • 如何實作custom type的Comparable

“Free” functions

  • 當做了Equatable和Comparable就可以另外享受其他另外的function。

Hashable

  • For value types (structs, enums) the compiler will generate Equatable and Hashable conformance for you automatically, but you will need to do it yourself for reference (class) types.

  • Hash values help you quickly find elements in a collection.

CustomStringConvertible

Key points

  • Protocols define a contract that classes, structs and enums can adopt.

  • By adopting a protocol, a type is required to conform to the protocol by implementing all methods and properties of the protocol.

  • A type can adopt any number of protocols, which allows for a quasi-multiple inheritance not permitted through subclassing.

  • You can use extensions for protocol adoption and conformance.

  • The Swift standard library uses protocols extensively. You can use many of them, such as Equatable and Hashable, on your own named types.

Last updated