Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-Only properties

Tags:

readonly

swift

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 {  } 
like image 210
AllocSystems Avatar asked Dec 21 '16 22:12

AllocSystems


People also ask

How do you set a readonly property?

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.

What is a read only property in Python?

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.

What is property explain how read only property is achieved?

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.


2 Answers

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)     } } 
like image 152
Rob Avatar answered Oct 26 '22 11:10

Rob


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 
like image 24
Luca Angeletti Avatar answered Oct 26 '22 12:10

Luca Angeletti