Read Only Properties

I need read-only help. I tried different ways, but just couldn't figure out how to compile it without errors. That is the question and what I was thinking about.

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

var isEquilateral: Int { } 
+6
source share
2 answers

Something like that? (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 me check it out

 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 
+7
source

If you want to save the saved property as read-only, use private(set) :

 private(set) var isEquilateral = false 

If this property is computed from other properties, then yes, use the computed property:

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

Source: https://habr.com/ru/post/1013405/


All Articles