4
votes

Swift is a pretty functional language and functional languages are all about expressions not statements which is why switch pattern matching puzzles me.

All the example are something like this:

switch x {
case > 0:
    print("positive")
case < 0:
    print("negative")
case 0:
    print("zero")
}

But I want to do something like this:

let result = switch x {
case > 0:
    "positive"
case < 0:
    "negative"
case 0:
    "zero"
}

Currently the only way i can see to do it is:

var result: String?

switch x {
case > 0:
    result = "positive"
case < 0:
    result = "negative"
case 0:
    result = "zero"
}

if let s = result {
    //...
}

Which is obviously no where near as elegant as the 'expression' based switch statement. Are there any work around or alternatives or is this something apple need to do to enhance the language?

1
Note that you don't need an optional in your last example, you can declare let result: String. The compiler verifies that a value is assigned to it before the variable is used. - Martin R
thanks martin i did not know that - Luke De Feo

1 Answers

7
votes

Switch statement cannot be directly used as an expression in Swift. But, there is a workaround to do what you want. It is possible to write the switch statement inside a closure like this:

let result : String = {
    switch x {
    case _ where x > 0:
        return "positive"
    case _ where x < 0:
        return "negative"
    default:
        return "zero"
    }
}()