Skip to content

Latest commit

 

History

History
69 lines (50 loc) · 2.63 KB

10.3 带有 Self 的协议 Protocols with Self Requirements.md

File metadata and controls

69 lines (50 loc) · 2.63 KB

第十章:协议 Protocol Protocol-Oriented Programming

10.3 带有 Self 的协议 Protocols with Self Requirements

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

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

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

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

最简单的是 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? 各位大佬可以把你们的想法分享出来。大家一起学习一下😄。

疑问后续❗️:

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

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

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

let x: Equatable = MonetaryAmount(currency: "EUR", amountInCents: 100)
// 会编译错误:因为 'Equatable' 协议中有 Self 或者关联类型的要求,
// 所以它只能被⽤用作泛型约束