Combining patterns as a functional expression in quick

Swift is a fairly functional language, and functional languages ​​are expressions, not expressions, which makes me match patterns.

The whole example looks 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 do this is:

var result: String?

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

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

Which is clearly not as convenient as expressing an expression operator based on an expression. Is there any work or alternatives or is this something apple needs to be done to improve the language?

+4
source share
1 answer

switch Swift. , , , . switch :

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

Source: https://habr.com/ru/post/1612455/


All Articles