为什么不能在异步函数中使用foreach?

Ada*_*eet 7 asynchronous swift

为什么使用异步函数时不能使用 foreach?我一直以为他们只是做同样的事情。

 let query = try? await store.collection("feedposts").getDocuments()
 let documents = query?.documents ?? []
Run Code Online (Sandbox Code Playgroud)

这很完美:

for document in documents {
            try? await store.collection("feedposts").document(document.documentID).collection("locked").document(uid).delete()
        }
Run Code Online (Sandbox Code Playgroud)

虽然这不会:

documents.forEach { document in
            try? await store.collection("feedposts").document(document.documentID).collection("locked").document(uid).delete()
        }
Run Code Online (Sandbox Code Playgroud)

Dar*_*ust 7

for x in y是一种语言功能并在当前范围内执行。所以await也是在当前作用域内执行的。

但这个forEach方法是一个带有特定参数的方法:

func forEach(_ body: (Self.Element) throws -> Void) rethrows
Run Code Online (Sandbox Code Playgroud)

您向它传递了一个块,如果您查看 的签名,body您会发现它缺少关键字async。因此,该块不会(保证)在异步环境中执行。但你只能await在一个async范围内使用,这body不能保证编译器,因此不允许你await在这里使用。

如果你想要一个支持async/await的forEach 方法,你需要自己实现Swift 项目中对 Swift 是否要提供异步forEach存在争议。