Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching as a functional expression in swift

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?

like image 353
Luke De Feo Avatar asked Mar 15 '23 10:03

Luke De Feo


1 Answers

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"
    }
}()
like image 159
aksh1t Avatar answered Mar 27 '23 05:03

aksh1t