Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Swift 2.0 Enumerations and Optionals Objects and Optionals Pattern Matching With Enums

Why 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 ==?

Nathan Tallack
Nathan Tallack
22,159 Points

I would love to know the answer to this also!

2 Answers

Greg Kaleka
Greg Kaleka
39,019 Points

Sort of. case .Nickel returns a boolean, when checking the value of coin. Just like in a switch statement.

It's identical to:

switch.swift
switch coin {
    case .Nickel:
        print("Statement")
    default:
        break
}

It's just a lot cleaner to write.

sugared.swift
if case .Nickel = coin { print("Statement") }
Nathan Tallack
Nathan Tallack
22,159 Points

Ah, so case works as a boolean evaluator not the =. Got it. :)

Greg Kaleka
Greg Kaleka
39,019 Points

Hi 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
Nathan Tallack
22,159 Points

So 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?