Swift协议扩展覆盖

我正在尝试使用Swift协议扩展,却发现这种行为令人困惑。您能帮我得到我想要的结果吗?


请参阅代码最后4行的注释。(如果需要,可以将其复制粘贴到Xcode7游乐场)。谢谢!!


//: Playground - noun: a place where people can play


import UIKit


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"


红糖糍粑
浏览 556回答 3
3回答

ABOUTYOU

简短的答案是协议扩展不执行类多态性。这是有一定道理的,因为协议可以被结构体或枚举所采用,并且因为我们不希望仅在没有必要的地方采用协议来引入动态调度。因此,在中getColor(),color实例变量(可能更准确地写为self.color)并不意味着您认为它会做什么,因为您正在以类多态的方式思考,而协议不是。所以这工作:let colorB = B().color // is "Red color" - OK...因为您要让一类学生解决问题color,但这并不能满足您的期望:let b = B().getColor() // is "Default color" BUT I want it to be "Red color"...因为该getColor方法完全在协议扩展中定义。您可以通过getColor在B中重新定义来解决此问题:class B: A, RedColor {    func getColor() -> String {        return self.color    }}现在,该类的getColor被调用了,它对什么self是一个多态的想法。

潇湘沐

我设法得到它的工作通过定义color上Color和切换执行列表B.没有太多的好,如果B必须是一个A虽然。protocol Color {    var color : String { get }}protocol RedColor: Color {}extension Color {    var color : String {        get {return "Default color"}    }}extension RedColor {    var color : String {        get {return "Red color"}    }}protocol PrintColor {    func getColor() -> String}extension PrintColor where Self: Color {    func getColor() -> String {        return color    }}class A : Color, PrintColor {}class B : RedColor, PrintColor {}let a = A().getColor() // "Default color"let b = B().getColor() // "Red color"
打开App,查看更多内容
随时随地看视频慕课网APP