![](/img/trans.png)
[英]Swift iOS -How to continue running a DispatchSemaphore combined with DispatchGroup()
[英]Swift -is it necessary to call continue when leaving a dispatchGroup
我有一组对象,我必须使用for-loop
和DispatchGroup
进行迭代。 将组留在for-loop
,是否需要调用continue
?
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(...
是的,绝对有必要调用continue
,因为您想避免继续执行循环体。
调用DispatchGroup.leave
不会退出当前范围,您需要调用continue
来实现。 leave
只会影响您对DispatchGroup
所做的任何事情 - 因此随后的notify
或wait
电话。
是的,按照这种方式编写, continue
很重要,因为您要确保enter
调用只有一个leave
调用。 由于您在if
测试之前调用enter
,那么您必须leave
并continue
。 如果您没有continue
语句,它将继续执行已调用leave
的后续代码。
但是,如果您只是在if
语句之后调用enter
, if
不需要此leave
/ continue
模式:
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) { ... }
然后我会采取更进了一步,并删除if
与continue
发言。 只需在for
循环中添加一个where
子句,完全不需要continue
:
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) { ... }
这完成了您的原始代码片段所做的工作,但更简洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.