iOS Functions in Swift Adding Power to Functions Default Values

Adrian Lawrence
Adrian Lawrence
392 Points

Stuck trying to get the carpetCost function to work. Continuously getting Binary operator error on all 3 cases of switch

//Area calulation for room # 2

let secondLength = 14 let secondWidth = 8

let secondArea = secondLength * secondWidth

//Area calculation for room #1

func area(length: Int, width: Int) -> Int { let areaOfRoom = length * width

return areaOfRoom

}

let areaOfFirstRoom = area(length: 10, width: 12) let areaOfSecondRoom = area(length: 15, width: 22)

// Argument Labels

func remove(havingValue value: String) { print(value) }

remove(havingValue: "A")

// Default Values func carpetCost(havingArea: Int, carpetColor color: String) -> Int { // Gray carpet - $1/sq ft // Tan carpet - $2/sq ft // Deep Blue carpet - $4/sq ft

var price = 0

switch color {
case "gray": price = area * 1
case "tan": price = area * 2
case "blue": price = area * 4
default: price = 0
}
return price

}

2 Answers

calp
calp
10,314 Points

I'm not sure if switch statements work the same way in Swift as to what I'm used to but it looks like you're missing break statements at the end of your cases.

Michelle Harrison
Michelle Harrison
8,782 Points

I know this is a few months old, but I decided to try solving it to improve my own code-reading skills and in case anyone else is having the same problem.

The issue is the lack of a local parameter name. From my novice understanding, Swift keeps trying to find the parameter name "area" for the cases, but there is no such name. In the code above, the integer (Int) it's supposed to be getting the number from is named "havingArea". If you add a local parameter name "area" to the external name, it solves the problem.

// Default Values
func carpetCost(havingArea area: Int, carpetColor color: String) -> Int {

Alternatively, you can forgo the local parameter name and just use "havingArea"

switch color {
case "gray": price = havingArea * 1
case "tan": price = havingArea * 2
case "blue": price = havingArea * 4
default: price = 0
}
return price

}