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 { }
To create a read-only field, use the readonly keyword in the definition. In the case of a field member, you get only one chance to initialize the field with a value, and that is when you call the class constructor. Beyond that, you'll would get an error for such attempt.
To define a readonly property, you need to create a property with only the getter. However, it is not truly read-only because you can always access the underlying attribute and change it. The read-only properties are useful in some cases such as for computed properties.
A read-only property in a class is similar to a readonly field. Both expose a value that users of the class can read, but not write. A readonly field is defined using the readonly modifier. A read-only property is defined by including a get accessor for the property, but not a set accessor.
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) } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With