Swift correct use of getters and setters

前端 未结 3 1407
野的像风
野的像风 2020-12-11 03:19

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

3条回答
  •  执念已碎
    2020-12-11 03:50

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

提交回复
热议问题