Search code examples
swiftpattern-matchingif-case

if-case pattern matching - Variable binding in a condition requires an initializer


I'm working through Big Nerd Ranch's Swift Programming book (2nd edition), and in the chapter on the Switch statement, there's a small section on in-cases and how to use them. When describing how to implement if-cases with multiple conditions, this is the code the book shows:

...
let age = 25

if case 18...35 = age, age >= 21 {
    print("In cool demographic and of drinking age")
} 

When I try implementing this (exactly as it is) in my Xcode playground, however, I get an error ("variable binding in a condition requires an initializer")

It seems that the age >= 21 bit is the actual problem, as this

let age = 25

if case 18...35 = age{
    // Same thing
}

works fine. What am I doing wrong in the multiple-condition code?


Solution

  • I'm working through Big Nerd Ranch's Swift Programming book (2nd edition) ...

    As mentioned at the official book web page, the book includes Swift Version 3.0 with Xcode 8.

    Probably, you are working on Xcode 7.x or earlier, in Swift 2, it should be:

    if case 18...35 = age where age >= 21 {
        print("In cool demographic and of drinking age")
    }
    

    Swift 3:

    if case 18...35 = age, age >= 21 {
        print("In cool demographic and of drinking age")
    }
    

    Remark: if the first code snippet has been complied at Xcode 8 playground, it will complain about following compile-time error:

    error: expected ',' joining parts of a multi-clause condition

    with a suggestion to change where to ,.

    The same grammar applied when working -for example- with optional binding:

    Swift 2:

    if let unwrappedString = optionalString where unwrappedString == "My String" {
        print(unwrappedString)
    }
    

    Swift 3:

    if let unwrappedString = optionalString, unwrappedString == "My String" {
        print(unwrappedString)
    }
    

    For more information about changing the where to , you might want to check Restructuring Condition Clauses Proposal.

    So, make sure to update the used IDE to the latest version (which compiles Swift 3).