Search code examples
iosswiftoopencapsulation

Get and Set on each field like in Java


I tried to look all over the internet to find out what is the best practice of encapsulating data in Swift. I only found some information about get and set method of an instance variables. They used to work pretty much like C#'s did set, but now they work as computed properties and one can't set them in their setters and can't get them in their getters. The question is: do people still create getter and setter for each property in the class in swift ? Like:

private var age: Int = 0
public func getAge() -> Int {
    return age
}
public func setAge(newAge: Int) {
    self.age = newAge
}

If not, then what is considered to be the best practice ? Thank You.


Solution

  • I use this type of syntax with computed vars to expose the getter and setters when the internals are more complex than what is shown here:

    internal var _age: Int = 0
    var age: Int {
        get {
            return _age
        }
        set {
            _age = newValue
        }
    }
    

    Plenty of syntaxic sugar to make it easy to hide complexity in some expressions.

    But most of the time I am happy with just exposing the plain var and be done with it:

    var age: Int = 0
    

    The advantage of this is that both ways are easily swappable when you want to do more work inside the getters and setters.