快速正确使用getter和setter

时间:2022-09-24 21:36:55

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.

谁能帮我理解swift中getter和setter的正确用法吗?我得到的印象和Java不一样。

Is this the correct usage in Swift to store and access a class variable?

这是Swift存储和访问类变量的正确用法吗?

class Person {
    private var name: String

    init(name: String) {
        self.name = name
    }

    func setName(name: String) {
        self.name = name
    }

    func getName() -> String {
        return name
    }
}

3 个解决方案

#1


11  

Swift provides a much more structured approach to getters and setters then Java.

Swift提供了一种更结构化的方法,以使getter和setter成为Java。

You can, but you should not, write setters and getters like you did in your code.

你可以,但是你不应该,像在你的代码中那样写setter和getter。

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.

没错!在Swift中,您可以使用willSet和didSet观察者进行此操作。

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 too be overwritten) with self.name while the new value is available with newValue.

在属性中写入新值之前,您要在这里编写您想要运行的代码。在这里,您可以使用self.name访问当前值(也将被覆盖),而新值可以使用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.

在属性中写入新值之后,您要运行的代码在这里。在这里,您可以使用oldValue访问旧值(已被覆盖),而新的值在self.name中可用。

Both willSet and didSet are optional (I am not talking about Optional Type! I mean you are not forced to write them :).

willSet和didSet都是可选的(我说的不是可选类型!)我的意思是,你并不是*写:)。

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

#2


3  

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.

如果你分配给self。,您将再次调用此方法。此外,不存在像旧的Java bean属性模式那样的“get”。最后,如果您确实需要在设置后使用属性计算或操作的方法,可以将它们构建到变量定义中。

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

#3


1  

This is how setter and getter works as in Java:

这就是setter和getter在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
        }
    }

}

#1


11  

Swift provides a much more structured approach to getters and setters then Java.

Swift提供了一种更结构化的方法,以使getter和setter成为Java。

You can, but you should not, write setters and getters like you did in your code.

你可以,但是你不应该,像在你的代码中那样写setter和getter。

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.

没错!在Swift中,您可以使用willSet和didSet观察者进行此操作。

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 too be overwritten) with self.name while the new value is available with newValue.

在属性中写入新值之前,您要在这里编写您想要运行的代码。在这里,您可以使用self.name访问当前值(也将被覆盖),而新值可以使用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.

在属性中写入新值之后,您要运行的代码在这里。在这里,您可以使用oldValue访问旧值(已被覆盖),而新的值在self.name中可用。

Both willSet and didSet are optional (I am not talking about Optional Type! I mean you are not forced to write them :).

willSet和didSet都是可选的(我说的不是可选类型!)我的意思是,你并不是*写:)。

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

#2


3  

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.

如果你分配给self。,您将再次调用此方法。此外,不存在像旧的Java bean属性模式那样的“get”。最后,如果您确实需要在设置后使用属性计算或操作的方法,可以将它们构建到变量定义中。

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

#3


1  

This is how setter and getter works as in Java:

这就是setter和getter在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
        }
    }

}