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 in Swift to store and access a class variable?
class Person {
private var name: String
init(name: String) {
self.name = name
}
func setName(name: String) {
self.name = name
}
func getName() -> String {
return name
}
}
Swift provides a much more structured approach to getters
and setters
than Java.
You can, but you should not, write setters and getters as 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 to 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
If you assign to self., you will just be calling this method again. Also, there is no "get" like the old Java bean property pattern. Finally, if you actually need to use methods for property computation or actions after setting, they can be built right into the variable definition.
class Person
{
private var name: String;
init( name: String )
{
self.name = name
}
}
should be sufficient for your simple case, although you can also
private var name: String {
didSet {
// updating something after setting
}
};
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