With Objective-C
, I can override the setText
function by following codes. The text
is a property of UITextField
, and I sub-class it for some custom UI design.
- (void)setText:(NSString *)text
{
[super setText:text];
....
}
My question is, how to do such thing by Swift ?
There is no such function setText
when I program with Swift. How to override the setter
and getter
methods of property with Swift ?
You can use variable observers in this case.
var variableName: someType = expression {
willSet(valueName) {
// code called before the value is changed
}
didSet(valueName) {
// code called after the value is changed
}
}
A practical example.
“class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}”
Excerpt From: Apple Inc. “The Swift Programming Language (Swift 2.1 Prerelease).” iBooks. https://itun.es/us/k5SW7.l
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