Lesser than or greater than in Swift switch statement

Pieter picture Pieter · Jul 27, 2015 · Viewed 59k times · Source

I am familiar with switch statements in Swift, but wondering how to replace this piece of code with a switch:

if someVar < 0 {
    // do something
} else if someVar == 0 {
    // do something else
} else if someVar > 0 {
    // etc
}

Answer

Aaron Brager picture Aaron Brager · Jul 27, 2015

Here's one approach. Assuming someVar is an Int or other Comparable, you can optionally assign the operand to a new variable. This lets you scope it however you want using the where keyword:

var someVar = 3

switch someVar {
case let x where x < 0:
    print("x is \(x)")
case let x where x == 0:
    print("x is \(x)")
case let x where x > 0:
    print("x is \(x)")
default:
    print("this is impossible")
}

This can be simplified a bit:

switch someVar {
case _ where someVar < 0:
    print("someVar is \(someVar)")
case 0:
    print("someVar is 0")
case _ where someVar > 0:
    print("someVar is \(someVar)")
default:
    print("this is impossible")
}

You can also avoid the where keyword entirely with range matching:

switch someVar {
case Int.min..<0:
    print("someVar is \(someVar)")
case 0:
    print("someVar is 0")
default:
    print("someVar is \(someVar)")
}