DEV Community

Cover image for Making properties read only outside their scope using private(set) in Swift
Tarik Dahic
Tarik Dahic

Posted on • Originally published at tarikdahic.com on

Making properties read only outside their scope using private(set) in Swift

I recently discovered Swift feature where setter for class and struct properties could be set to private while getter is internal or publicly accessed. This allows us to expose properties to the outside world without worrying if someone is going to change them in the future. I mostly do this to make dependencies of some type accessible.

The example below shows how could we use this in a class or a struct.

class Example {
  // prop will have an internal access modifier
  private(set) var prop: Type

  // prop with public access modifier
  public private(set) var prop: Type
}

Enter fullscreen mode Exit fullscreen mode

prop can be changed (set) only in the scope of the encapsulated struct or class but the outside world can only read it.

Setting a private setter only works with properties marked as var and not let because properties marked with let are constants and by nature they are immutable.

This Swift feature could also be used in cases when we have a read-only property backed by another private property. Something like this:

class Example {
  private var _prop: Type

  var prop: Type {
    get {
      return _prop
    }
  }
}

// Using private(set) makes code more readable and reduces the complexity:

class Example {
  private(set) var prop: Type
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)