Joe Scotto Joe Scotto - 27 days ago 8
Swift Question

Can computed properties have multiple properties on the setter

I'm very new to swift and have been having a hard time figuring out computed properties. Is there a way to pass in multiple properties to a setter or are you limited to just one? I'm attempting the following code but receive this error

Expected '{' to start setter definition
and
Expected '}' after setter parameter name


I'm confused as to the whole type defining in swift also and have tried passing a dictionary into the setter but that then causes issues with my return type.

The code I currently have:

struct Shape {
var height: Int = 0
var width: Int = 0

var area: Int {
set (width, height) {
self.width = width
self.height = height
}

get {
return self.width * self.height
}
}
}

Answer

To pass multiple values to a setter you have to declare the type of the property accordingly, for example

struct Shape {
   var height: Int = 0
   var width: Int = 0

   var area: (Int, Int) {
      set  {
         self.width = newValue.0
         self.height = newValue.1
      }

      get {
         return (width, height)
      }
   }
}

var shape = Shape()
shape.area = (120, 60)

print(shape.area) // (120, 60)

As mentioned in the comment the type of the property, setter and getter must be the same.