Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift property observer in protocol extension?

Consider the following:

protocol ViewControllable: class {   typealias VM: ViewModellable   var vm: VM! { get }   func bind() }  extension ViewControllable {   var vm: VM! {     didSet {       bind()     }   } } 

I'm trying to observe vm property and call bind whenever it is injected. But this doesn't compile with error saying:

Extensions may not contain stored properties

which makes sense since protocol cannot enforce properties to be stored or computed.

Is this possible to accomplish without introducing class inheritance?

In other words, Can I observe the change of a property inside protocol extension?

like image 369
Daniel Shin Avatar asked Nov 23 '15 03:11

Daniel Shin


People also ask

What is property Observer in Swift?

Property Observers. Property observers observe and respond to changes in a property's value. Property observers are called every time a property's value is set, even if the new value is the same as the property's current value. You can add property observers in the following places: Stored properties that you define.

Can extensions have properties Swift?

Extensions in Swift can: Add computed instance properties and computed type properties. Define instance methods and type methods. Provide new initializers.

CAN protocol have properties Swift?

A protocol can have properties as well as methods that a class, enum or struct conforming to this protocol can implement. A protocol declaration only specifies the required property name and type.

Why extensions Cannot have stored properties?

error: extensions may not contain stored properties . It means that Swift doesn't support stored properties inside the extension. Therefore, we cannot use the toggleState property to keep the internal state of our toggle button. For this reason, we need a workaround.


1 Answers

No, this is explicitly disallowed. See Extension: Computed Properties:

Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.

Keep in mind that if this were legal, it would add some non-trivial confusion about order of execution. Imagine there were several extensions that added didSet, and the actual implementation also had a didSet. What order should they run in? This doesn't mean it's impossible to implement, but it could be somewhat surprising if we had it.

like image 167
Rob Napier Avatar answered Sep 28 '22 04:09

Rob Napier