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
}
swiftswitch statement
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
}
Best Answer
Here's one approach. Assuming
someVar
is anInt
or otherComparable
, you can optionally assign the operand to a new variable. This lets you scope it however you want using thewhere
keyword:This can be simplified a bit:
You can also avoid the
where
keyword entirely with range matching: