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
}
}
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
}
@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)")
}
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