How can I implement didSet
on MyProtocol var
through an extension?
I need to run some specific code after it has been set.
I tried this, but I get this error:
Extensions may not contain stored properties
protocol MyProtocol {
var contact: MyContact? { get set }
}
extension MyProtocol {
var contact: MyContact? {
didSet {
// some code
}
}
}
From the docs:
Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html#//apple_ref/doc/uid/TP40014097-CH24-ID151
If you want to set a default value of contact
, then it has to be a computed property.
extension MyProtocol {
var contact: MyContact? {
return MyContact()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With