3

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?

enharmonics
  • 259
  • 3
  • 9
  • 1
    Are you using Swift 2 by any chance? (If so, why?) Compiles fine for me in Swift 3.1 – Hamish Apr 04 '17 at 14:15
  • As @Hamish mentioned, it complies fine here too... what's the version of Swift are you using? – Ahmad F Apr 04 '17 at 14:16
  • Swift 2.2 does indeed give that error message. Swift 2 syntax would be `if case 18...35 = age where age >= 21 {`. – vacawama Apr 04 '17 at 14:21
  • A quote from the section titled **Necessary Hardware and Software**: *This book is written for Swift 3.0 and Xcode 8.0. Many of the examples will not work with older versions of Xcode.* – vacawama Apr 04 '17 at 14:29
  • But really you should upgrade to Swift 3 – the latest version of Xcode doesn't even *support* Swift 2. – Hamish Apr 04 '17 at 14:29

1 Answers1

4

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).

Ahmad F
  • 30,560
  • 17
  • 97
  • 143