devxoul / if_

Swift if-else statement as an expression (Experimental)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

if_

Swift

Swift if-else statement as an expression.

At a Glance

if-else

let point = 70
let grade = if_(point >= 90) {
    "A"
}.else_if_(point >= 80) {
    "B"
}.else_ {
    "C"
}
print(point) // "C"

If there's no else_ chaining, the expression will return nil for else cases.

let point = 70
let grade = if_(point >= 90) {
    "A"
}.else_if_(point >= 80) {
    "B"
}
print(point) // nil

if-let-else

let value: Any = "Hello"
let string = if_let_(value as? String) {
    $0 + " world!"
}
print(string) // "Hello world!"

Use , to bind multiple optionals.

let someValue = if_let_(optional1, optional2, optional3) {
    $0 + $1 + $2
}

if-let-where

let value: Any = 12
let result = if_let_(value as? Int, where_: { $0 % 2 == 0 }) {
    $0 * 2
}
print(value) // 24

License

if_ is under MIT license. See the LICENSE file for more info.

About

Swift if-else statement as an expression (Experimental)

License:MIT License


Languages

Language:Swift 95.7%Language:Objective-C 4.3%