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 trialAnjali Pasupathy
2,017 PointsWhy do if case statements use the assignment symbol rather than the equality symbol?
The example given used the syntax,
if case .Nickel = coin { print("Statement") }
Why does if case syntax use = rather than ==?
2 Answers
Greg Kaleka
39,021 PointsSort of. case .Nickel
returns a boolean, when checking the value of coin. Just like in a switch statement.
It's identical to:
switch coin {
case .Nickel:
print("Statement")
default:
break
}
It's just a lot cleaner to write.
if case .Nickel = coin { print("Statement") }
Nathan Tallack
22,160 PointsAh, so case works as a boolean evaluator not the =. Got it. :)
Greg Kaleka
39,021 PointsHi Anjali,
So this is a little tricky to explain, because it's sort of syntactical sugar, as Pasan mentions. The equal sign is not a comparison operator here. Instead, it's telling the compiler what .Nickel is a case of. Put another way, it's telling the compiler what we're switching on.
The check is "If the case is a .Nickel". You can sort of think about a double equals between case
and .Nickel
. This is the same way you might think about a switch statement. Here, though, we're not in a switch statement, so we have to tell the compiler what to check the case of, hence the = coin
. We're not checking to see if it's a coin - we know it's a coin!
Anyway, like I said this is a tricky concept - I do wish Pasan had spent a bit more time explaining it. Let me know if this makes sense!
Cheers,
Greg
Nathan Tallack
22,160 PointsSo in this case .Nickel = coin returns a boolean? How can that be? It would need to be a boolean to be a conditional qualifer right?
Nathan Tallack
22,160 PointsNathan Tallack
22,160 PointsI would love to know the answer to this also!