Swift forEach – break

We cannot break from a forEach block in Swift using break statement.

The following throws a compiler error during build time as shown in the screenshot.

main.swift

</>
Copy
var primes:[Int] = [2, 3, 5, 7, 11]

primes.forEach { prime in
    print(prime)
    break
}

Output

Break inside Swift forEach raises Compiler Error during Buildtime

As mentioned in the error, ‘break’ statement is only allowed inside a loop, if, do or switch statements.

Conclusion

Concluding this Swift Tutorial, we could not break from a forEach statement. forEach ensures that the code block is executed for each of the element in the iterable.