Private variables in swift

Viewed 2811

When creating a class, what is the difference between these 2 implementations of creating a custom class in regards to security. They both work the exact same as far as I've used them, but have heard using private variables is the proper way to create classes

class Person {

    var name:String
    var age:Int

    init(name: String, age: Int){
        self.name = name
        self.age = age
    }
}

and

class Person {

    private var _name: String
    private var _age: Int

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

    var age: Int {
        set {
            self._age = newValue
        } get {
            return _age
        }
    }

    init(name: String, age: Int){
        self._name = name
        self._age = age
    }
}
1 Answers

private is definitely recommended to use but only in cases when you want that kind of privacy for your properties.

Your second code is not ensuring any kind of privacy. That's just adding more code unnecessarily.

There can be a scenario where you want to keep the write access private to the type (class/struct) and allow read access outside the type. For that you can use private(set) access modifier with your properties, i.e.

class Person {
    private(set) var name: String
    private(set) var age: Int

    init(name: String, age: Int){
        self.name = name
        self.age = age
    }
}
Related