Private setter "set()" in Swift
Swift private setter
Solution #1 using a public function
struct A {
private var a: String
public init(a: String) {
self.a = a
}
func getA() -> String {
return a
}
}
let field = A(a:"a")
field.getA()
Solution #2 using private setter. In this case setter has a lower access level then geter
struct A {
private(set) var a: String
public init(a: String) {
self.a = a
}
}
let field = A(a:"a")
field.a
In the docs, in the first code sample under the heading "Getters and Setters" you can see that to have a private setter, the syntax looks like this :
private (set) var center: Point {...
Some clarification :
private
in Swift works a little differently - it limits access to property/method to the scope of a file. As long as there is more then one class in a file, they will be able to access all their contents. In order for private
"to work", you need to have your classess in separate files.