Getter Setter method swift

We have to understand first what getter and setter method is used for. So, we will deal with variables here. When we have a variable whose value we get according to some calculations from class then get method is called and when we want to set its value according to some constraints then use set method.

It can be understood from following example :

In this example, you deal with two variables. sideLength and perimeter. We want to get perimeter when we giveĀ sideLength and we want to set sideLength when we give the perimeter.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triangle with sides of length \(sideLength)." } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") print(triangle.perimeter) triangle.perimeter = 9.9 print(triangle.sideLength) |