Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Jolian Chan
Jolian Chan
4,154 Points

Have a problem with Swift Switch statement

Hi,

I'm practicing the Swift Switch statement, here is the codes

let sales2017 = 4000000.00
let firstTierBounsTarget = 5000000.00
let secondTierBounsTarget = 4000000.00
let thirdTierBounsTarget = 3000000.00

switch sales2017 {
case sales2017 > firstTierBounsTarget: print("2017 Bonus: \(sales2017 * 0.005)")
case sales2017 > secondTierBounsTarget: print("2017 Bonus: \(sales2017 * 0.003)")
case sales2017 > thirdTierBounsTarget: print("2017 Bonus: \(sales2017 * 0.001)")
default: print("No Bonus Annual This Year!!")
}

I get an error on line 7-9, it says " Expression pattern of type 'Bool' cannot match values of type Double." Can everyone point out my mistakes?

Thanks

2 Answers

Everton Carneiro
Everton Carneiro
15,994 Points

Switch and IF statements are not the same. You cannot compare two values in a case as you do in IF statement because that's is not how switch statement works. You need to check each case regarding the object you are checking. For example:

let number = 10

switch number {
case 10:
    print("It is ten")
default:
    break
}

For the purpose of your code, you can use a case with a range of values. Remember when use conditional statements you need to be specific because for example if a value is higher than 50, it is also higher than 40 and 30. In your code you can do something like this:

let sales2017 = 4000000.00
let firstTierBounsTarget = 5000000.00
let secondTierBounsTarget = 4000000.00
let thirdTierBounsTarget = 3000000.00

switch sales2017 {
case firstTierBounsTarget...100000000000000.00: print("2017 Bonus: \(sales2017 * 0.005)")
case secondTierBounsTarget...firstTierBounsTarget: print("2017 Bonus: \(sales2017 * 0.003)")
case thirdTierBounsTarget...secondTierBounsTarget: print("2017 Bonus: \(sales2017 * 0.001)")
default: print("No Bonus Annual This Year!!")
}

I hope that helps.

Jolian Chan
Jolian Chan
4,154 Points

Everton Carneiro, now I got it, thanks for your help.