Read-Only properties
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)
}
}
A read-only property is a property with getter
but no setter
. It is always used to return a value.
class ClassA {
var one: Int {
return 1
}
var two: Int {
get { return 2 }
}
private(set) var three:Int = 3
init() {
one = 1//Cannot assign to property: 'one' is a get-only property
two = 2//Cannot assign to property: 'two' is a get-only property
three = 3//allowed to write
print(one)//allowed to read
print(two)//allowed to read
print(three)//allowed to read
}
}
class ClassB {
init() {
var a = ClassA()
a.one = 1//Cannot assign to property: 'one' is a get-only property
a.two = 2//Cannot assign to property: 'two' is a get-only property
a.three = 3//Cannot assign to property: 'three' setter is inaccessible
print(a.one)//allowed to read
print(a.two)//allowed to read
print(a.three)//allowed to read
}
}
Something like this? (as suggested by @vacawama in the comments)
struct Triangle {
let edgeA: Int
let edgeB: Int
let edgeC: Int
var isEquilateral: Bool {
return (edgeA, edgeB) == (edgeB, edgeC)
}
}
Let's test it
let triangle = Triangle(edgeA: 5, edgeB: 5, edgeC: 5)
triangle.isEquilateral // true
or
let triangle = Triangle(edgeA: 2, edgeB: 2, edgeC: 1)
triangle.isEquilateral // false