Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to stop a block literal in swift

Tags:

swift

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     } } 
like image 247
William Hu Avatar asked Nov 19 '15 01:11

William Hu


People also ask

How do you stop a forEach loop in Swift?

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.

How do you break a loop in Swift?

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).

What is block in Swift?

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.


2 Answers

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] 
like image 137
R Menke Avatar answered Sep 20 '22 23:09

R Menke


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 } 
like image 44
Zaporozhchenko Oleksandr Avatar answered Sep 19 '22 23:09

Zaporozhchenko Oleksandr