My SuerClass is UICollectionViewCell
which has a property:
var selected: Bool
My class is
MyClass : UICollectionV
If all we want it do some extra functionality after the selected
property as been set, we can simply override to add a property observer:
override var selected: Bool {
didSet {
if self.selected {
// do something
}
}
}
Updated Answer for Swift 5:
override var isSelected: Bool {
didSet {
if self.isSelected {
// do something
}
}
}
If we care about what the previous value of selected
was, we can access it via oldValue
:
didSet {
if self.selected == oldValue {
return
}
// do something
}
Updated Answer for Swift 5:
didSet {
if self.isSelected == oldValue {
return
}
// do something
}
And don't forget, we can use willSet
as well if we need to do something just before the value is changed.
I was curious what would happen when we've got a large hierarchy of classes each adding their own stuff in willSet
and didSet
property observers, so I created the following test:
class ClassA {
var _foo: Int = 0
var foo: Int {
set(newValue) {
println("Class A setting foo")
self._foo = newValue
}
get {
return self._foo
}
}
}
class ClassB: ClassA {
override var foo: Int {
willSet {
println("Class B will set foo")
}
didSet {
println("Class B did set foo")
}
}
}
class ClassC: ClassB {
override var foo: Int {
willSet {
println("Class C will set foo")
}
didSet {
println("Class C did set foo")
}
}
}
Now, if we create an object of ClassC
and set its foo
property:
var c: ClassC = ClassC()
c.foo = 42
We get the following output:
Class C will set foo
Class B will set foo
Class A setting foo
Class B did set foo
Class C did set foo
So, it's important to note a few things from this...
willSet
is called before its parent's willSet
.didSet
is called after its parent's didSet
.The first two points make a bit of sense. And actually, this makes property observers much more appealing. Effectively, Swift forces our hand into going up and down the heirarchy in the appropriate manner and nicely splits it out into two separate methods. Swift also prevents us (I believe) from overriding a parent class's property, but also still lets us observe changes to that property--this is much better than Objective-C's approach.
But the third point is probably the most important. Be careful--you can easily get bogged down in a massive heirarchy of didSet
and willSet
code that's slowing down what should be a pretty quick process: setting a property's value.