簡體   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