Reputation: 1971
this is point example introduced pint structure setter getter provided by apple how can make only setter private
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
Upvotes: 15
Views: 18190
Reputation: 34175
Swift private setter
Solution #1 using a public function
struct MyStruct {
private var a: String
init(a: String) {
self.a = a
}
func getA() -> String {
return a
}
}
let myStruct = MyStruct(a: "Hello World")
let a = myStruct.getA()
Solution #2 using private setter. In this case setter has a lower access level then geter
struct MyStruct {
private(set) var a: String
init(a: String) {
self.a = a
}
}
let myStruct = MyStruct(a: "Hello World")
let a = myStruct.a
Upvotes: 13
Reputation: 8006
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.
Upvotes: 37
Reputation: 3661
You can refine the struct Rect as follows. This will allow you to only get center but not set it.
struct Rect {
var center:Point {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
var origin = Point()
var size = Size()
}
Upvotes: 3