Reputation: 19572
I have a group of objects that I have to iterate through using a for-loop
and DispatchGroup
. When leaving the group inside the for-loop
, is calling continue
necessary?
let group = DispatchGroup()
for object in objects {
group.enter()
if object.property == nil {
group.leave()
continue // does calling this have any effect even though the group is handling it?
}
// do something with object and call group.leave() when finished
}
group.notify(...
Upvotes: 1
Views: 2051
Reputation: 437442
Yes, the way this is written, the continue
is critical, as you want to make sure that the enter
call has a single leave
call. Since you're calling enter
before the if
test, then you must leave
and continue
. If you don’t have the continue
statement, it will proceed with the subsequent code which is calling leave
already.
But this leave
/continue
pattern is not needed if you just call enter
after the if
statement:
let group = DispatchGroup()
for object in objects {
if object.property == nil {
continue
}
group.enter()
// do something with object and call group.leave() when finished
}
group.notify(queue: .main) { ... }
I'd then take that a step further and remove that if
with the continue
statement. Just add a where
clause to the for
loop, eliminating the need for the continue
at all:
let group = DispatchGroup()
for object in objects where object.property != nil {
group.enter()
// do something with object and call group.leave() when finished
}
group.notify(queue: .main) { ... }
This accomplishes what your original code snippet did, but is more concise.
Upvotes: 1
Reputation: 54706
Yes, it is absolutely necessary to call continue
, since you want to avoid continuing the execution of the body of your loop.
Calling DispatchGroup.leave
does not exit the current scope, you need to call continue
to achieve that. leave
only affects whatever you are doing with the DispatchGroup
- so consequent notify
or wait
calls.
Upvotes: 2