Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift correct use of getters and setters

Tags:

ios

swift

swift2

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
    }
}
like image 540
MikeJ Avatar asked Nov 30 '15 13:11

MikeJ


2 Answers

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
    }
}

Ok but in java getter and setters do allow me to add custom logic to be executed before or after the value is changed.

Right! In Swift, you can do this using the willSet and didSet observers.

willSet(newValue)

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.

didSet(oldValue)

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.

Example

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
like image 58
Luca Angeletti Avatar answered Oct 04 '22 19:10

Luca Angeletti


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
    }
};
like image 23
Peter DeWeese Avatar answered Oct 04 '22 19:10

Peter DeWeese