Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend default implementation (with an extension) adding a didSet on a property?

Tags:

xcode

ios

swift

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
        }
    }
}
like image 566
EvGeniy Ilyin Avatar asked Apr 24 '16 00:04

EvGeniy Ilyin


1 Answers

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()
  }
}
like image 193
Ahmed Onawale Avatar answered Sep 29 '22 14:09

Ahmed Onawale