简体   繁体   English

"如何并行使用 Swift async\/await"

[英]How to use Swift async/await in parallel

Consider the code below:考虑下面的代码:

class UserProfile
{
    private var img: UIImage? {
       didSet { /* update ui */ }
    }
    private var bio: String? {
       didSet { /* update ui */ }
    }

    private func loadImage() async -> UIImage? {
        // ... 
    }

    private func loadBio() async -> String? {
        // ...
    }

    public func loadData() async {
        async let img = loadImage()
        async let bio = loadBio()

        self.img = await img
        self.bio = await bio
    }
}

you could try something like this:你可以尝试这样的事情:

func loadData() async {
    await withTaskGroup(of: Void.self) { group in
        group.addTask { self.img = await loadImage() }
        group.addTask { self.bio = await loadBio() }
    }
}

我相信使用元组可以解决这个问题:

(self.img, self.bio) = await (img, bio)<\/code>

"

You can do it like this:你可以这样做: 在此处输入图像描述

You can also see the swift documentation- https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID643您还可以查看 swift 文档- https://docs.swift.org/swift-book/LanguageGuide/Concurrency.html#ID643

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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