Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2: guard in for loop?

Tags:

what is the correct way to use guard inside a for loop?

for (index,user) in myUsersArray.enumerate() {

    guard user.id != nil else {
        print("no userId")
        //neither break / return will keep running the for loop
    }

    if user.id == myUser.id {

        //do stuff

    }
}
like image 282
longbow Avatar asked Oct 01 '15 21:10

longbow


2 Answers

There are a few ways to make some conditionals:

You can put a condition for whole for. It will be called for each iteration

for (index, user) in myUsersArray.enumerate() where check() {}
for (index, user) in myUsersArray.enumerate() where flag == true {}

You can check something inside for and skip an iteration or stop the loop:

for (index, user) in myUsersArray.enumerate() {
    guard check() else { continue }
    guard flag else { break }
}

In your case I will be write something like this:

for (index, user) in myUsersArray.enumerate() {
    guard let userId = user.id, userId == myUser.id else { continue }

    // do stuff with userId
}
like image 92
Arsen Avatar answered Oct 11 '22 02:10

Arsen


@Arsens answer is correct but I think this is easier to understand

let ints = [1,2,3,4,5]

for (index,value) in ints.enumerate() {

        guard value != 1 else {
            print("Guarded \(value)")
            continue
        }

        print("Processed \(value)")
}
like image 43
Lev Landau Avatar answered Oct 11 '22 02:10

Lev Landau