我有一个带有单个变量的协议
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)
}
}
}
答案 0 :(得分:0)
您应该做的是实现变量观察者didSet
或willSet
以下是基于您的代码的代码段
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 代码段