Read-Only properties

AllocSystems picture AllocSystems · Dec 21, 2016 · Viewed 31.8k times · Source

I need help with "read-only" in swift. I tried various ways, but simply couldn't figure out how to compile it without errors. Here's the question and what i thought of.

Create a read-only computed property named isEquilateral that checks to see whether all three sides of a triangle are the same length and returns true if they are and false if they are not.

var isEquilateral: Int {

}

Answer

Rob picture Rob · Dec 21, 2016

If you want a "read-only" stored property, use private(set):

private(set) var isEquilateral = false

If it is a property calculated from other properties, then, yes, use computed property:

var isEquilateral: Bool {
    return a == b && b == c
}

For the sake of completeness, and probably needless to say, if it is a constant, you’d just use let:

let isEquilateral = true

Or

struct Triangle {
    let a: Double
    let b: Double
    let c: Double

    let isEquilateral: Bool

    init(a: Double, b: Double, c: Double) {
        self.a = a
        self.b = b
        self.c = c

        isEquilateral = (a == b) && (b == c)
    }
}