Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: private get and public set

Tags:

swift

What I found until now is the scenario of a public get and private set like visible below.

private(set) var distanceTravelled: Double

I want it the other way around. Of course the following is not working.

private(get) public var distanceTravelled: Double
like image 383
Sven Mäurer Avatar asked Jun 18 '15 07:06

Sven Mäurer


People also ask

What is Public Private set Swift?

public(get) private(set) var foo:String. to be doubly explicit. The goal is that foo should have a getter which is accessible from outside the module, but a private setter. Using only private(set) means that the getter is internal - so not accessible outside the module.

Can getters and setters be private?

The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.

What are get and set in Swift?

To create computed properties, Swift offers you a getter and (an optional) setter method to work with. A getter method is used to perform a computation when requested. A setter method is an optional method. It can be used to modify a related property.


3 Answers

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
}
like image 149
giorashc Avatar answered Oct 16 '22 19:10

giorashc


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.

like image 43
Damien_The_Unbeliever Avatar answered Oct 16 '22 18:10

Damien_The_Unbeliever


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.

like image 38
Clay Bridges Avatar answered Oct 16 '22 18:10

Clay Bridges