Set value to computed properties in SWIFT

I think you're misunderstanding the concept of a computed property. By definition, a computed property is one whose value you cannot set because, well, it's computed. It has no independent existence. The purpose of the setter in a computed property is not to set the value of the property but to set the values of other properties, from which the computed property is computed. Take, as an example, a square. Its side length is a var property s and the area is a computed property whose getter returns s*s and whose setter sets s to be the square root of newValue (the new area). The setter does not set the area. It sets the side length from which the area will get computed the next time you access the area property.


A computed property is just that: A computed value, in your case from width and height. There is no instance variable where the properties value is stored, you cannot change the "computed property itself".

And it makes no sense: If the area could be set to a different value, what should the getter method return? This new value or width*height?

So most probably you want a read-only computed property for the area:

var area: Int {
    get {
        return width * height
    }
}

As you already noticed, the setter can modify the values of other stored properties, for example:

class Rectangle {
    var width : Int = 20
    var height : Int = 400

    var area: Int {
        get {
            return width * height
        }
        set(newArea){
            // Make it a square with the approximate given area:
            width = Int(sqrt(Double(newArea)))
            height = width
        }
    }
}

But even then the results may be surprising (due to integer rounding):

let r = Rectangle()
r.area = 200
println(r.area) // 196