Steve O'Sullivan Steve O'Sullivan - 2 months ago 8
Swift Question

How to code a switch statement switching on a range in Swift 3

If I use either the .. or ... range operators in the following code, the playground throws an error. What is the proper way to code this in Swift 3 (I am working with a book written using Swift 2.3)

Xcode 8 with Swift 3

let osxVersion: Int = (1...12)
switch osxVersion {
case 1...8:
print("Some big cat!")
case 9:
print("Mavericks")
case 10:
print("Yosemite")
case 11:
print("El Capitan")
case 12:
print("Sierra")
default:
print("Appledonttellmenuthin!!")
}

Answer

You have it correct.

let osxVersion = 7
switch osxVersion {
case 0...5:
    print("hi")
case 6...8:
    print("hello")
default:
    print("hey")
}

Run in a playground, that will print "hello"

Comments