xcode - Swift 协议(protocol)扩展覆盖

标签 xcode swift swift2

我正在试验 Swift 协议(protocol)扩展,我发现这种行为非常令人困惑。你能帮助我如何得到我想要的结果吗?

查看代码最后 4 行的注释。 (如果需要,您可以将其复制粘贴到 Xcode7 Playground )。谢谢!!

protocol Color { }
extension Color {  var color : String { return "Default color" } }

protocol RedColor: Color { }
extension RedColor { var color : String { return "Red color" } }


protocol PrintColor {
    
     func getColor() -> String
}

extension PrintColor where Self: Color {
    
    func getColor() -> String {
        
        return color
    }
}


class A: Color, PrintColor { }
class B: A, RedColor { }


let colorA = A().color // is "Default color" - OK
let colorB = B().color // is "Red color" - OK


let a = A().getColor() // is "Default color" - OK
let b = B().getColor() // is "Default color" BUT I want it to be "Red color"

最佳答案

简短的回答是协议(protocol)扩展不做类多态性。这在一定程度上是有道理的,因为协议(protocol)可以被结构或枚举采用,并且因为我们不希望仅仅采用协议(protocol)来引入不必要的动态调度。

因此,在 getColor() 中,color 实例变量(可能更准确地写为 self.color)不会意味着你认为它做了什么,因为你正在考虑类多态性而协议(protocol)不是。所以这有效:

let colorB = B().color // is "Red color" - OK

...因为您要求解析颜色,但这并没有达到您的预期:

let b = B().getColor() // is "Default color" BUT I want it to be "Red color"

...因为 getColor 方法完全在协议(protocol)扩展中定义。您可以通过在 B:

中重新定义 getColor 来解决此问题
class B: A, RedColor {
    func getColor() -> String {
        return self.color
    }
}

现在类的 getColor 被调用,并且它有一个关于什么是 self 的多态概念。

关于xcode - Swift 协议(protocol)扩展覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31431753/

相关文章:

swift - flatMap() 在单个事件上调用两次

ios - 在 AVPlayer 上添加 ActivityIndi​​cator 并删除 addObserver

iphone - 从命令行分发 ipa 到 iTunes connect

java - Swift 和可见性声明

swift - 将变量值传递给不同的类 - Swift

ios - 快速传递参数?

xcode - 在 Swift 中从 Firebase 获取单独的数据

ios - 乘以文本字段错误?

iphone - 如何在ios应用程序中使用post数据和json

iphone - 双击按钮