Carol Smith
Carol Smith

Reputation: 61

How to use get and set in Swift

I have a block of simple code calculating the area & perimeter of a rhombus.

 var perimeterOfRhombus: Double {
        get {
            let twoSides1 = sideLength1 + sideLength1
            let twoSides2 = sideLength2 + sideLength2
            let finalPerimeter = twoSides1 + twoSides2
            return finalPerimeter
        } set {
      }
    }

What I am missing is the set section.

I want it to show what sideLength1 and sideLength2 were in the beginning.

I am not sure what newValue is used for, when it has no value.

It does work without using set, but I see on Apple's swift language guide that set and get usually go together.

If set is really not needed in this code, what is it normally used for anyways?

Upvotes: 6

Views: 28958

Answers (2)

Saurabh Sharma
Saurabh Sharma

Reputation: 51

Computed property in swift using get and set

class Square {
    var side: Double = 0.0
    var area: Double {
        get {
            return side*side
        }
        set(newArea) {
            print(newArea)
            self.side = sqrt(newArea)
        }
    }
}

let obj = Square()
obj.side = 10.0
print(obj.area)

Upvotes: 1

Ajith Renjala
Ajith Renjala

Reputation: 5152

You should be referring to Read-Only Computed Properties instead of Computed Properties.

A computed property with a getter but no setter is known as a read-only computed property.It always returns a value, and cannot be set to a different value.

 var perimeterOfRhombus: Double {
  let twoSides1 = sideLength1 + sideLength1
  let twoSides2 = sideLength2 + sideLength2
  let finalPerimeter = twoSides1 + twoSides2
  return finalPerimeter
 }

Computed Properties do not actually store a value. Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.

Computed properties, including read-only properties must be set as a variable and not a constant.

 struct Square {
  var edge: Double = 0

  var area: Double {
    get {
      return edge * edge
    }
    set (newArea){
      edge = sqrt(newArea)
    }
  }
 }

In this case, setter can't be used to set the value of the property but to set the values of other properties, from which the computed property is computed.

About newValue, it's called Shorthand Setter Declaration - If a computed property’s setter does not define a name for the new value to be set, a default name of newValue is used.

So, the above example becomes

 struct Square {
  var edge: Double = 0

  var area: Double {
    get {
      return edge * edge
    }
    set {
      edge = sqrt(newValue) //someSquare.area = 25 (25 is newValue)
    }
  }
 }

Upvotes: 18

Related Questions