Get and Set on each field like in Java

300 views Asked by At

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.

3

There are 3 answers

2
John Difool On BEST ANSWER

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.

0
Christopher Ian  Stern On

I don't think you need to create getX/setX methods, because you can always change from a stored to a computed property without having to change the source code of the clients. Just like you could change the bodies of your getAge & setAge methods, so I do not see what is gained in swift by not letting clients use age.

0
Justin On

if you want to access the property (Age) itself, you can always get/set it directly.

let theGirlsAge = Age; // Get
Age = theBoysAge; // Set

Getters and Setters are used for define relationship between the property and other properties.

public func getAge() -> Int {
    return theBoysAge 
}
public func setAge(newAge: Int) {
    theGirlsAge = newAge
}