Can someone please help me understand the correct use of getters and setters in swift. I get the impression its not the same as say Java.
Is this the correct usage i
Swift provides a much more structured approach to getters and setters than Java.
You can, but you should not, write setters and getters like you did in your code.
Instead (if you are using stored properties) just declare the property with a visibility non private (e.g. internal in my example). This way callers outside of your class will be able to see the property and change it.
class Person {
var name: String {
willSet(newValue) {
print("\(self.name) is going to be renamed as \(newValue)")
}
didSet(oldValue) {
print("\(oldValue) has been renamed as \(self.name)")
}
}
init(name: String) {
self.name = name
}
}
Right! In Swift you can do this using the willSet and didSet observers.
You write here the code you want to run before a new value is written in the property.
Here you can access the current value (that is going too be overwritten) with self.name while the new value is available with newValue.
You write here the code you want to run after a new value is written in the property.
Here you can access the old value (that has been overwritten) with oldValue while the new value is available in self.name.
Both willSet and didSet are optional (I am not talking about Optional Type! I mean you are not forced to write them :).
If you don't need to run some code just before or after the property has been changed, just omit them.
let aVerySmartPerson = Person(name: "Walter White")
aVerySmartPerson.name = "Heisenberg"
// > Walter White is going to be renamed as Heisenberg
// > Walter White has been renamed as Heisenberg