繁体   English   中英

Swift - 离开 dispatchGroup 时是否需要调用 continue

[英]Swift -is it necessary to call continue when leaving a dispatchGroup

我有一组对象,我必须使用for-loopDispatchGroup进行迭代。 将组留在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所做的任何事情 - 因此随后的notifywait电话。

是的,按照这种方式编写, continue很重要,因为您要确保enter调用只有一个leave调用。 由于您在if测试之前调用enter ,那么您必须leavecontinue 如果您没有continue语句,它将继续执行已调用leave的后续代码。

但是,如果您只是在if语句之后调用enterif不需要此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) { ... }

然后我会采取更进了一步,并删除ifcontinue发言。 只需在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM