Swift 5.x 协议 protocol

2020-07-05  本文已影响0人  ShenYj

e.g.

protocol SomeProtocol {
    
}

struct SomeStructure: FirstProtocol, AnotherProtocol {
    
}

class SomeClass: SomeSuperClass, FirstProtocol, AnotherProtocol {
    
}
1. 属性要求

e.g.

protocol FullyNamed {
    var fullName: String { get }
}

struct Person: FullyNamed {
    // 可读可写 存储型属性
    var fullName: String
}

class Starship: FullyNamed {
    var name: String
    init(name: String) {
        self.name = name
    }
    // 实现协议的可读属性 计算型属性
    var fullName: String {
        "Starship \(name)"
    }
}

let john = Person(fullName: "john")
let enterprise = Starship(name: "Enterprise")

print(john.fullName)
print(enterprise.fullName)

输出结果:

john
Starship Enterprise

e.g. 类型属性

protocol SomeProtocol {
    static var someTypeProperty: Int { get set }
}
2. 方法要求
3. mutating方法要求
4. 初始化器要求
protocol SomeProtocol {
    init(someParameter: Int) 
}
5. 初始化器要求的类实现
class SomeClass: SomeProtocol {
    required init(someParameter: Int) {
        
    }
}

e.g.

protocol SomeProtocol {
    init()
}

class SomeSuperClass {
    init() {
        
    }
}

class SomeSubClass: SomeSuperClass, SomeProtocol {
    required override init() {
        
    }
}
6. 将协议作为类型
7. 协议继承
8. 类专用的协议

e.g.

protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {
    
}
9. 协议组合

e.g.

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, \(celebrator.name) you're \(celebrator.age)!")
}

let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(to: birthdayPerson)

输出结果:

Happy birthday, Malcolm you're 21!
10.可选协议要求
上一篇 下一篇

猜你喜欢

热点阅读