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
Expected '}' after setter parameter name
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
}
}
}
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.