[英]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.