简体   繁体   中英

Swift correct use of getters and setters

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 (eg 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

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

This is how setter and getter works as in Java:

class Person {
    private var _name
    private var _age
    // .... other properties

    var name: String {
        get {
            return _name
        }
        set {
            _name = newValue
        }
    }

    var age: String {
        get {
            return _age
        }
        set {
            _age = newValue
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM