Swift: Unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do

Viewed 1833

I am trying to break from 'if' condition within a for loop and getting this error. Below is the code:

var isPresent = false
arrayList.forEach { item in
  if item.contains("xyz") {
     isPresent = true
     break
   }
} 

I am getting this errorL

Unlabeled break is only allowed inside a loop or switch, a labeled break is required to exit an if or do"

Can I not use unlabeled break here?

1 Answers

Closures can only return out of their local scope, there's no non-local returns (like in Ruby or Kotlin). You can't break out of them like this.

You're using the wrong function anyway, so you can entirely sidestep the issue:

let isPresent = arrayList.contains(where: { $0.contains("xyz") })
Related