為什么我在使用異步函式時不能使用 foreach?我一直認為他們只是做同樣的事情。
let query = try? await store.collection("feedposts").getDocuments()
let documents = query?.documents ?? []
這完美地作業:
for document in documents {
try? await store.collection("feedposts").document(document.documentID).collection("locked").document(uid).delete()
}
雖然這不是:
documents.forEach { document in
try? await store.collection("feedposts").document(document.documentID).collection("locked").document(uid).delete()
}
uj5u.com熱心網友回復:
for x in y
是一種語言功能,在當前范圍內執行。所以await
也是在當前范圍內執行的。
但是該forEach
方法是一個接受特定引數的方法:
func forEach(_ body: (Self.Element) throws -> Void) rethrows
你傳給它一個塊,如果你看一下你的簽名,body
你會發現它缺少async
關鍵字。因此,該塊不會(保證)在異步環境中執行。但是你只能await
在一個async
范圍內使用,這body
不能保證編譯器,因此它不允許你在await
這里使用。
如果你想要一個支持 async/await 的forEach
方法,你需要自己實作它。Swift 是否會提供異步在 Swift 專案中forEach
存在爭議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/508475.html