Private setter "set ()" in Swift

this is an example provided by getter setter setter pint provided by apple , how can only setter private be done

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) } } } 
+6
source share
3 answers

You can refine the structure of Rect as follows. This will allow you to get only the center, but not install 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() } 
+1
source

In the docs in the first code example, under the heading "Getters and Setters", you can see that in order to have your own setter, the syntax is as follows:

 private (set) var center: Point {... 

Some clarifications: private in Swift works a little differently - it restricts access to the property / method to the scope of the file. As long as there is more than one class in the file, they will be able to access all of their contents. In order for private "work", you need to have your own coolness in separate files.

+17
source

Decision No. 1

 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() 

Decision No. 2

 struct A { private(set) var a: String public init(a: String) { self.a = a } } let field = A(a:"a") field.a 
0
source

Source: https://habr.com/ru/post/1245529/


All Articles