Assign conditional expression in Swift?

后端 未结 1 1058
借酒劲吻你
借酒劲吻你 2021-01-12 18:03

Is there a way in Swift to assign conditional expressions similar to this

let foo = if (bar == 2) {
        100
    } else {
        120
    }
相关标签:
1条回答
  • 2021-01-12 18:06

    You can use a closure to initialize an immutable:

    let foo: Int = {
        if bar == 2 {
            return 100
        } else {
            return 120
        }
    }()
    

    The advantage of using a closure is that it's a function, so you can use any complex logic inside, implemented in a clean way and not through nested ternary operators. It can be a switch statement, it can be obtained as the return value of a function followed by some calculations, it can be a pattern matching case, it can be a combination of them all, etc.

    Said in other words, it's the same as initializing with the return value of a function, but the difference is that the function is inline and not somewhere else, with readability benefits.

    Just for completeness, if the variable is mutable, you can use deferred initialization:

    var foo: Int
    
    // Any statement here
    
    if bar == 2 {
        foo = 100
    } else {
        foo = 120
    }
    
    // Other statements here
    
    myFunc(foo)
    

    so you can declare a mutable variable, and initialize it anywhere in the same scope, but before using it the variable must be initialized.

    Update: Since Swift 2.0, deferred initialization also works with immutables.

    0 讨论(0)
提交回复
热议问题