Protocols 笔记

属性、普通方法、初始化方法 0、Property Requirements A protocol can require any conforming type to provide an insta


0、Property Requirements

A protocol can require any conforming type to provide an instance property or type property with a particular name and type.

protocol SomeProtocol { var mustBeSettable: Int { get set } var doesNotNeedToBeSettable: Int { get }}protocol AnotherProtocol { static var someTypeProperty: Int { get set }}

1、Method Requirements

Protocols can require specific instance methods and type methods to be implemented by conforming types.

和普通方法的定义没啥区别,只是没有 {} 主体,但定义的参数不能使用默认值

2、Mutating Method Requirements

mutating 只用于struct 或 enum,实现时可以不用写 mutating 关键字

protocol Togglable { mutating func toggle()}enum OnOffSwitch: Togglable { case off, on mutating func toggle() { // mutating 可不写 switch self { case .off: self = .on case .on: self = .off } }}var lightSwitch = lightSwitch.toggle()

3、Initializer Requirements

Protocols can require specific initializers to be implemented by conforming types.

可以实现为 designated initializer 或 convenience initializer,需要用 required 修饰符修饰,不过如果是 final 就可以不用。

protocol SomeProtocol { init(someParameter: Int)}class SomeClass: SomeProtocol { required init(someParameter: Int) { // initializer implementation goes here }}

如果是子类,需要 required 和 override 两个修饰符

protocol SomeProtocol { init()}class SomeSuperClass { init() { // initializer implementation goes here }}class SomeSubClass: SomeSuperClass, SomeProtocol { // "required" from SomeProtocol conformance; "override" from SomeSuperClass required override init() { // initializer implementation goes here }}

4、Failable Initializer Requirements

A failable initializer requirement can be satisfied by a failable or nonfailable initializer on a conforming type.

A nonfailable initializer requirement(上面提到的) can be satisfied by a nonfailable initializer or an implicitly unwrapped failable initializer.

5、Protocols as Types

  • As a parameter type or return type in a function, method, or initializer
  • As the type of a constant, variable, or property
  • As the type of items in an array, dictionary, or other container

6、Delegation 或 DataSource

7、Adding Protocol Conformance with an Extension

You can extend an existing type to adopt and conform to a new protocol。

8、Declaring Protocol Adoption with an Extension

If a type already conforms to all of the requirements of a protocol, but has not yet stated that it adopts that protocol, you can make it adopt the protocol with an empty extension:


protocol TextRepresentable { var textualDescription: String { get }}struct Hamster { var name: String var textualDescription: String { return "A hamster named /(name)" }}extension Hamster: TextRepresentable {}

9、Protocol Inheritance (组合)

A protocol can inherit one or more other protocols and can add further requirements on top of the requirements it inherits.

protocol InheritingProtocol: SomeProtocol, AnotherProtocol { // protocol definition goes here}

10、Class-Only Protocols

You can limit protocol adoption to class types (and not structures or enumerations) by adding the class keyword to a protocol’s inheritance list.

protocol SomeClassOnlyProtocol: class, SomeInheritedProtocol { // class-only protocol definition goes here}

11、Protocol Composition(temporary local protocol 临时性的)

Protocol compositions have the form SomeProtocol & AnotherProtocol. You can list as many protocols as you need to, separating them by ampersands (&).

protocol Named { var name: String { get }}protocol Aged { var age: Int { get }}struct Person: Named, Aged { var name: String var age: Int}func wishHappyBirthday(to celebrator: Named & Aged) { print("Happy birthday, /(, you're /(celebrator.age)!")}let birthdayPerson = Person(name: "Malcolm", age: 21) wishHappyBirthday(to: birthdayPerson) // Prints "Happy birthday, Malcolm, you're 21!"

12、Checking for Protocol Conformance(is, as?, as!)

Type Casting 笔记

13、Optional Protocol Requirements

optional 关键字,加 @objc 属性,只能作用是 class

@objc protocol CounterDataSource { @objc optional func increment(forCount count: Int) -> Int @objc optional var fixedIncrement: Int { get }}class Counter { var count = 0 var dataSource: CounterDataSource? func increment() { if let amount = dataSource?.increment?(forCount: count) { count += amount } else if let amount = dataSource?.fixedIncrement { count += amount } }}

14、Protocol Extensions (且可以提供默认实现)

Protocols can be extended to provide method and property implementations to conforming types.

15、Providing Default Implementations

You can use protocol extensions to provide a default implementation to any method or computed property requirement of that protocol.

协议的扩展(上面提示的是 类的扩展 遵从某协议)提供默认的实现,如果自己实现了就不使用默认的实现。

Protocol requirements with default implementations provided by extensions are distinct from optional protocol requirements. Although conforming types don’t have to provide their own implementation of either, requirements with default implementations can be called without optional chaining.

16、Adding Constraints to Protocol Extensions

When you define a protocol extension, you can specify constraints that conforming types must satisfy before the methods and properties of the extension are available.

protocol SomeProtocol {}extension SomeProtocol where Self: UIView {}protocol AnotherProtocol {}extension Collection where Iterator.Element: AnotherProtocol {}