Mischa
Mischa

Reputation: 17269

Override the setter of a protocol-defined variable and use the getter from the protocol's default implementation

I have a protocol with a single variable

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

for which I implement a default 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 ""
        }
    }
}

Now I make several classes conform to this protocol. In these classes I want to override the localizationKey's setter but use the default implementation for its getter, for example:

extension UILabel: Localizable {

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

}

(How) can I do that?

Upvotes: 1

Views: 1599

Answers (1)

Adolfo
Adolfo

Reputation: 1862

What you should do is implement the variable observer didSet or willSet

Here's a snippet based on your code

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: I forget it. Extension cannot override properties, you should use the willSet snippet on a class

Upvotes: 0

Related Questions