Search code examples
swiftoperator-keywordternary

swift: about ternary operator Question. Why my code is error code??? Please tell me why I'm wrong


swift: about ternary operator Question. Why my code is error code??? Please tell me why I'm wrong.


var arr = [0,1,2,3,4,5,6,7,8]

var result = 0;

for a in 0..<arr.count{
    for b in 1..<arr.count - 1{
        for c in 2..<arr.count - 2 {
            arr[a] + arr[b] + arr[c] <= input[1] ? result = arr[a] + arr[b] +arr[c] : continue
        }
    }
}

[this is my error] [1]: https://i.sstatic.net/UdiUB.png


Solution

  • In Swift, the ternary condition operator is an expression which takes the form

    <condition> ? <expression if true> : <expression if false>
    

    Expressions are part of larger statements, and the ternary specifically is one which evaluates to either the expression after the ?, or the one after the : depending on the truth of the condition.

    continue, however, is not an expression but a statement on its own, which means that it cannot be on either side of the ternary.

    Thinking about this another way: expressions evaluate to some value (e.g., can be put on the right-hand-side of an assignment, like x = <some expression>), while statements do not (e.g., it doesn't make sense to write x = continue).

    You will need to express this in the form of a regular if-statement then:

    if arr[a] + arr[b] + arr[c] <= input[1] {
        result = arr[a] + arr[b] +arr[c]
    } else {
        continue
    }
    

    Note that the above code might be grammatically correct (in that it will compile), but it is unlikely to be what you mean: the loop will automatically continue at the end of execution even if arr[a] + arr[b] + arr[c] <= input[1] by default, which means that your result may get overwritten later in the loop. It seems likely that you mean something like

    outer_loop: for a in 0 ..< arr.count {
        for b in 1 ..< arr.count - 1 {
            for c in 2 ..< arr.count - 2 {
                if arr[a] + arr[b] + arr[c] <= input[1] {
                    result = arr[a] + arr[b] + arr[c]
    
                    // `break` would only exit the `c` loop, but with this label
                    // we can exit all loops at once.
                    break outer_loop
                }
            }
        }
    }