覆盖协议定义变量的setter,并使用协议默认实现中的getter

时间:2017-03-21 16:45:32

标签: swift override protocols extension-methods default-implementation

我有一个带有单个变量的协议

protocol Localizable {
    var localizationKey: String { get set }
}

我实现了默认getter

extension Localizable {
    var localizationKey: String {
        get {
            assert(true, "❌ Do not use this getter! 
                          The localizationKey is a convenience variable 
                          for setting a localized string.")
            return ""
        }
    }
}

现在我让几个类符合这个协议。在这些类中,我想覆盖localizationKey的setter,但使用其getter的默认实现,例如:

extension UILabel: Localizable {

    var localizationKey: String {
        get {
            // ❓ Use default implementation from protocol extension here
        }
        set {
            text = LocalizedString(forKey: newValue)
        }
    }

}

(怎么样)我可以这样做吗?

1 个答案:

答案 0 :(得分:0)

您应该做的是实现变量观察者didSetwillSet

以下是基于您的代码的代码段

protocol Localizable {
    var localizationKey: String { get set }
}


extension Localizable {
    var localizationKey: String {
        get {
            return ""
        }
    }
}

class UILabel: Localizable {

    var localizationKey: String {
        willSet
        {
            text = LocalizedString(forKey: newValue)
        }
    }

}
PD:我忘记了。扩展无法覆盖属性,您应该在类

上使用 willSet 代码段