Here is the code:
var _selected: Bool = false {
didSet(selected) {
let animation = CATransition()
animation.type = kCATransitionFade
animation.duration = 0.15
self.label.layer.addAnimation(animation, forKey: "")
self.label.font = self.selected ? self.highlightedFont : self.font
}
}
Why the variable is "_selected" instead of "selected"?
There are a few nuances to different use cases, but generally an underscore means "ignore this". When declaring a new function, an underscore tells Swift that the parameter should have no label when called — that's the case you're seeing.
An underscore in front usually indicates an instance variable as opposed to a local variable. It's merely a coding style that can be omitted in favor of "speaking" variable names and small classes that don't do too many things. Follow this answer to receive notifications.
The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.
It's simply a coding style that shouldn't apply to Swift code.
Developers often mark things with an underscore to indicate that it should be private.
That said, there IS a practical use for the underscore _. Read more about Local and External Parameter Names for Methods.
So how do you avoid using _selected? Right now you have two variables when you already have the one you need (selected).
Removing the _ will require you to override the member variable (how this should be done).
override var selected: Bool {
didSet {
println("Hello, \(selected)")
}
}
Additionally, a table view cell will have an overridable method setSelected(selected:animated) that might be worth exploring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With