Create a Setter Only in Swift

Aggressor picture Aggressor · Oct 8, 2014 · Viewed 19.2k times · Source

When I create a setter such as:

var masterFrame: CGRect {
    set {
        _imageView.frame = newValue
        _scrollView.frame = newValue
    }
}

It's forcing me to make a getter, which I don't want to do.

Is there any way to create a setter in Swift without a getter?

Answer

eonil picture eonil · May 7, 2015

Well if I really have to, I would use this.

Swift compiler supports some attributes on getters, so you can use @available(*, unavailable):

public subscript(index: Int) -> T {
    @available(*, unavailable)
    get {
        fatalError("You cannot read from this object.")
    }
    set(v) {
    }
}

This will clearly deliver your intention to the code users.