If-case syntax confusing me

Hi all,

I’m at the end of the chapter and Listing 5.12 is:

 let age = 25
 if case 18...35 = age {
     print("Cool demographic")
 }

I feel the syntax is inconsistent because we are using “=” instead of “==” Is there some sort of value binding going on or pattern matching that I don’t get?

If I fiddle with Listing 5.13 (with multiple conditions) and change the “>=” to “=” I get an error:

 if case 18...35 = age, age >= 25 {print ("text...")} // ->  fiddling works
 if case 18...35 = age, age = 25 {print ("text...")} // -> doesn't work
 if case 18...35 = age, age == 25 {print ("text...")} // -> fiddling further works

in the second condition I have to use “==”

this works:
if case age = 25, age == 25 {print("text...") }

but this doesn’t:
if case age == 25, age == 25 {print("text..") } // doesn't work

So my question is, why is the first condition different from the rest, that I have to use “=” instead of “==” to check the condition is true?

Thanks for your answers!

It is just syntax; you just need to get used to it :slight_smile:

In the context of an if statement, you can think of case 18…35 = age as being the same as the boolean expression age >= 18 && age <=35; and case 25 = age as being the same as age == 25.

Note, however that neither case 18…32 = age nor case 25 = age are boolean expressions.

// The following if statements have the same effect.

if case 18...35 = age {
    print ("age is in 18...35")
}

if age >= 18 && age <= 35 {
    print ("age is in 18...35")
}

The above if case statement can also be written like this:

let between_18_and_35 = {(v:Int) -> Bool in
    switch v {
    case 18...25:
        return true
    default:
        return false
    }
}

if between_18_and_35 (age) {
    print ("age is in 18...35")
}

Hi ibex10,

thanks for your reply. I guess thats just the way it is then!

Alain