1

As I am going through the Swift Language Guide, I am trying to see whether I can implement a Struct that will have a width property which will include a getter/setter that will get/set its own value. Is that possible? Example:

struct Resolution {
    static var standardResWidth = 1024
    var height = 0
    var width: Int {
        get {
            return self.width;
        }
        set {
            if newValue > Resolution.standardResWidth {
                width = newValue;
            }
        }
    }
}

By the look of things, the compiler of Playground throws an error on this one. As soon as I make a separate variable though, it works:

struct Resolution {
    static var standardResWidth = 1024
    var height = 0
    var width = 0
    var setWidth: Int {
        get {
            return width;
        }
        set {
            if newValue > Resolution.standardResWidth {
                width = newValue;
            }
        }
    }
}
George Katsanos
  • 13,524
  • 16
  • 62
  • 98

0 Answers0