【问题标题】:Override the setter of a protocol-defined variable and use the getter from the protocol's default implementation覆盖协议定义变量的 setter 并使用协议默认实现中的 getter
【发布时间】:2017-08-13 11:39:56
【问题描述】:

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

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)
        }
    }

}

(如何)我可以这样做吗?

【问题讨论】:

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


    【解决方案1】:

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

    这是基于您的代码的 sn-p

    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)
            }
        }
    
    }
    

    警察:我忘记了。扩展不能覆盖属性,你应该在一个类上使用 willSet sn-p

    【讨论】:

    • 当您定义class UILabel: Localizable 时,您在此处使用继承。但是,我想在 UILabel(和其他现有的 UI 组件)上定义一个 extension 以便向现有类添加行为。
    • 在扩展中,当您实现协议中定义的属性时,您需要同时实现 getter 和 setter。简单地使用willSet 会导致编译错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    相关资源
    最近更新 更多