Property access level

You,Swift

In this short article I go over how we can create a property with private setter and public getter. For instance there are times where we don’t want our property to be modified out of the class we declared in but we want it to be accessed globally. Let me show you how we can simply achieve that 😃. Are you ready?

For example let’s look at the class below:

class Person {
  public var name: String
  private var id: UUID
}

In the above code, the Person class has two properties, name which access level is specified as public and id which is private and it can’t be accessed outside of Person class. What can we do if we want it to be accessed outside of the class but we want it to be modified within the Person class only?

Well, this is pretty straightforward in Swift. We can change the access level to private (set).

class Person {
  public var name: String
  private(set) var id: UUID
}

This will make set private, but get gets default access control level (default is internal). If we want to make it public. We can do that as well. Its pretty straightforward and cool, isn’t it? 😃

class Person {
  public var name: String
  public private(set) var id: UUID
}

This means we can’t modify the id property our side of the Person class, but we can read it globally. We just have to specify access level twice, once for variables (both getter and setter) and second one is for the setter.

I hope you learned something from this short article, thank you for reading it. Please, share it with others if you think it is useful.

© Ezaden Seraj.