Grigori Jlavyan
Grigori Jlavyan

Reputation: 1971

Private setter "set()" in 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)
        }
    }
}

Upvotes: 15

Views: 18190

Answers (3)

yoAlex5
yoAlex5

Reputation: 34175

Swift private setter

[Swift access modifiers]

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

Losiowaty
Losiowaty

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

Pradeep K
Pradeep K

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

Related Questions