Like below, i want to stop the literal by something like break
var numbers = [1,2,3,4] numbers.forEach { if $0 % 2 == 0 { 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. As mentioned in the error, 'break' statement is only allowed inside a loop, if, do or switch statements.
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in switch statement (covered in the next chapter).
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
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]
Since you want to stop on the first match, you should use first
and not forEach
:
numbers.first { (number) -> Bool in return number % 2 == 0 }
Do something with the result (the first even number on the list):
if let firstEvenNumber = numbers.first(where: { $0 % 2 == 0 }) { print("The first even number on the list is \(firstEvenNumber)") }
Bonus: create a list of all the even numbers using filter
:
let allEvenNumbers = numbers.filter { $0 % 2 == 0 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With