Any way to stop a block literal in swift

forEach is not a loop (it is a block passed to a loop, but not a loop itself), or more accurately, forEach is not part of Swift’s Control Flow. Which is why you can’t use break or continue.

Just use a for-in loop.


Example :

var numbers = [ 1,2,3,4]

func firstEvenNumber(inArray array: [Int]) -> Int? {

    var firstMatch : Int?

    for number in numbers {
        if (number % 2) == 0 {
            firstMatch = number
            break
        }
    }
    return firstMatch
}

firstEvenNumber(inArray: numbers) // 2

You can use return inside the forEach closure, but it does not break the loop, it only returns the block in the current pass.

var numbers = [ 1,2,3,4]

func evenNumbers(inArray: [Int]) -> [Int] {

    var matches : [Int] = []

    numbers.forEach{
        if $0 % 2 == 0 {
            matches.append($0)

            // early return on even numbers
            // does not stop forEach
            // comparable to a continue in a for in loop
            return
        }

        // only reached on uneven numbers
    }
    return matches
}

evenNumbers(numbers) // [2,4]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)