Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private setter "set()" in Swift

Tags:

swift

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)
        }
    }
}
like image 937
Grigori Jlavyan Avatar asked Mar 22 '16 07:03

Grigori Jlavyan


People also ask

What is the use of private set in Swift?

However, the access level for the numberOfEdits property is marked with a private(set) modifier to indicate that the property's getter still has the default access level of internal, but the property is settable only from within code that's part of the TrackedString structure.

What is private set?

Private set intersection is a secure multiparty computation cryptographic technique that allows two parties holding sets to compare encrypted versions of these sets in order to compute the intersection.

What is get set method 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 accessing the property. A setter method is an optional method. It can be used to modify a property that relates to the computed property.


2 Answers

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.

like image 80
Losiowaty Avatar answered Sep 28 '22 06:09

Losiowaty


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
like image 32
yoAlex5 Avatar answered Sep 28 '22 08:09

yoAlex5