我有一个协议
protocol Example: class {
var value: Bool { get set }
func foo()
func bar()
}
和扩展:
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...
}
}
- 当
value
设置为 时true
,我想foo()
被调用 - 当
value
设置为 时false
,我想bar()
被调用
但是,我不想didSet{ }
在每个符合的类中冗余地实现逻辑Example
但是,如果我尝试didSet{ }
在扩展中添加逻辑,Xcode 会说“扩展不能包含存储的属性”。
添加默认属性观察逻辑而不必复制/粘贴到每个符合的类中的最佳实践是什么?
目标:
我希望任何子类都UIView
符合我的协议Expandable
。我的协议的要求是isExpanded: Bool
、expand()
和collapse
。我想isExpanded = true
打电话expand()
,isExpanded = false
打电话collapse()
(很像设置的行为isHidden
)。但是对于 UIView 的每个子类,我不想重写任何逻辑。我只想让课程符合Expandable
,然后直接进入设置isExpanded
。