Swift: private get and public set

I don't believe this is possible. To quote from the documentation:

You can give a setter a lower access level than its corresponding getter

That is, you can only alter the access in one direction, and that is to make the setter more restrictive than the getter.


If you want a public setter but a private getter for this var you can declare it as private:

private var distanceTravelled: Double

and create a public method for setting this variable:

public func setDistanceTravelled(distanceTravelled: Double) {
    self.distanceTravelled = distanceTravelled
}

This is possible, as of Xcode 10.2 / Swift 5.

You combine a computed property with an @available attribute, like this:

public var distanceTravelled: Double {
  @available(*, unavailable) 
  get { internalDistanceTravelled }

  set { internalDistanceTravelled = newValue }
}

private var internalDistanceTravelled: Double

Note that if you make distanceTravelled visible to Objective-C, the unavailable will not extend there.

Tags:

Swift