I have a protocol
protocol Example: class {
var value: Bool { get set }
func foo()
func bar()
}
And extension:
extension Example {
// var value: Bool { // Error: Extensions must not contain stored properties
// didSet {
// switch value {
// case true:
// foo()
// case false:
// bar()
// }
// }
// }
func foo() {
// logic...
}
func bar() {
// logic...
}
}
- When
valueis set totrue, I wantfoo()to be called - When
valueis set tofalse, I wantbar()to be called
However, I do not want to redundantly implement didSet{ } logic into every class that conforms to Example
But, if I try to add didSet{ } logic into the extension, Xcode says "Extensions must not contain stored properties".
What is the best practice for adding default property-observing logic without having to copy/paste into every conforming class?
The Goal:
I want any subclass of UIView to conform to my protocol Expandable. The requirements of my protocol are isExpanded: Bool, expand(), and collapse. I want isExpanded = true to call expand(), and isExpanded = false to call collapse() (much like the behavior of setting isHidden). But for every subclass of UIView, I don't want to have rewrite any logic. I'd like to just make the class conform to Expandable, and jump right in to setting isExpanded.