gpt4 book ai didi

swift - 调用了错误的多个约束扩展实现

转载 作者:行者123 更新时间:2023-11-28 15:21:28 25 4
gpt4 key购买 nike

我正在实现一个结构,其组成如下:

protocol ProtocolA {
func doStuff()
}

protocol ProtocolB { }

extension ProtocolA {
func doStuff() {
print("From protocol A")
}
}

extension ProtocolA where Self: ProtocolB {
func doStuff() {
print("From protocol B")
}
}

我有以下类(class):

class MyClassA: ProtocolA {
func letsDoSomething() {
self.doStuff()
}
}

class MyClassB: MyClassA, ProtocolB {
}

发生的事情是:

let ia = MyClassA()
ia.letsDoSomething() // From protocol A (OK!)

let ib = MyClassB()
ib.letsDoSomething() // From protocol A (Wrong!)

我当然不希望有第二个答案。

Swift Programming Launguage 中所述指南:

If a conforming type satisfies the requirements for multiple constrained extensions that provide implementations for the same method or property, Swift will use the implementation corresponding to the most specialized constraints.

为什么符合ProtocolBib类没有调用最专业的扩展实现?

我知道调用类仍然是 MyClassA 但由于实例来自 MyClassB 符合协议(protocol) ProtocolB 我仍然期待调用最专业的实现。

最佳答案

问题是 MYClassB 继承自 MyClass A。Swift 的方法调度规则永远不会调用这个子类的实现,并且在协议(protocol)一致性的情况下始终使用默认实现。像这样尝试相同的情况

class MyClassA: ProtocolA {
func letsDoSomething() {
self.doStuff()
}
}

class MyClassB: ProtocolA, ProtocolB {
}


let ia = MyClassA()
ia.letsDoSomething() // From protocol A (OK!)

let ib = MyClassB()
ib.doStuff() // From protocol A (Wrong!)

关于swift - 调用了错误的多个约束扩展实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45917993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com