[swift 进阶]读书笔记-第十章:协议 C10P3 带有 Self 的协议 Protocols with Self Requirements

第十章:协议 Protocol Protocol-Oriented Programming

10.3 带有 Self 的协议 Protocols with Self Requirements

本小节的知识点比较单一,主要是围绕带有Self的协议来说的git

什么是带有 Self 要求的协议?

当咱们的协议中须要引入自身相关的参数或者返回自身相关的返回值的时候用self (书中并无明确的解锁,外国大佬写的书直接上了就干demo了。上面对self的解释是我查了不少资料的结果,看起来的确是废话,哈哈但让解释也只能这样解释😄)github

带有 Self 要求的协议在行为上和那些带有关联类型的协议很类似swift

最简单的是 Equatable函数

protocol Equatable {
    static func ==(lhs: Self, rhs: Self) -> Bool
}
复制代码

咱们来写一个最简单的带有self协议的Demo。 一眼一看就会了😼学习

protocol GHEqual {
    ///这里引入了self
    static func == (lhs: Self, rhs: Self) -> Bool
}

class Person: NSObject, GHEqual {
    
    var gender: String = ""
    ///这里实现的时候系统会自动将self替换成了具体的类型。
    static func == (lhs: Person, rhs: Person) -> Bool {
        if lhs.gender == rhs.gender {
            return true
        } else {
            return false
        }
    }
}

let personA = Person()
personA.gender = "male"

let personB = Person()
personB.gender = "male"

let isSame = (personA == personB) ///true
复制代码
小疑问❓:

在咱们的认知中上面用到的 == 应该是对象方法。 为嘛在协议中声明的时候会用 static func? 我目前的结论是在协议中写操做符号时 对象方法也是用static func? 各位大佬能够把大家的想法分享出来。你们一块儿学习一下😄。ui

疑问后续❗️:

后来我查阅资料,在StackOverflow中有人提到了这个问题 Why must a protocol operator be implemented as a global function? 其大概解释就是 因为swift语法的缘由,操做符的实现必须是一个全局函数。 感兴趣的同窗能够看看问题中大牛们的回答。spa

咱们不能简单地用 Equatable 来做为类型进行变量声明:

和上一节的关联类型协议同样,咱们不能把带有self的协议做为类来变量声明code

let x: Equatable = MonetaryAmount(currency: "EUR", amountInCents: 100)
// 会编译错误:由于 'Equatable' 协议中有 Self 或者关联类型的要求,
// 因此它只能被⽤用做泛型约束
复制代码

文章源文件地址,你们若是有更好的想法和观点欢迎交流对象

相关文章
相关标签/搜索