Skip to content

iOS private(set) - Getters and Setters

Platform Language License

You assign a lower access level by writing private(set).

Its work like "Public getter and Private setter"

//MARK:- Foo
class Foo {
    private var name: String
    private var ID: String

    //initialize
    init(name:String, ID:String){
        self.name = name
        self.ID = ID
    }
}

We will end with error, when to try to access private variable.

PrivateAccessLevel

But we can access with new and awesome way to do this in a single line.

Then change private access level to private(set)

//MARK:- Foo
class Foo {
    private(set) var name: String
    private var ID: String

    //initialize
    init(name:String, ID:String){
        self.name = name
        self.ID = ID    
    }
}

So you can easy access the private variable, constant, property, or subscript.

//Access class value from Foo
let fooObjc = Foo.init(name: "test", ID: "9900")
print(fooObjc.name)

Try to use with

fileprivate(set)
private(set)
internal(set) 

to change the access level of this synthesized setter in exactly the same way as for an explicit setter in a computed property.

Tip

"This property can be read, but cannot be set from the outside"


Let's grow together 🌱

Cheers 🍻