zl程序教程

您现在的位置是:首页 >  前端

当前栏目

SwiftUI WWDC21 新特性之 MainActor 取代 DispatchQueue.main.async

async 特性 SwiftUI main 取代 WWDC21
2023-09-11 14:18:30 时间

SwiftUI WWDC21 新特性之 MainActor 取代 DispatchQueue.main.async

MainActor 是什么

一个单例actor,其执行者相当于主调度队列。

宣言

@globalActor actor MainActor

官方代码

@MainActor
class Photos: ObservableObject {

    @Published private(set) var items: [SpacePhoto] = []

    // Updates `items` to a new, random list of photos.
    func updateItems() async {
        let fetched = await fetchPhotos()
        items = fetched
    }

    // Fetches a new, random list of photos.
    func fetchPhotos() async -> [SpacePhoto] {
        var downloaded: [SpacePhoto] = []
        for query in Photos.keys {
            let url = SpacePhoto.request(key: query)
            if let photo = await fetchPhoto(from: url) {
                downloaded.append(photo)
            }
        }
        return downloaded
    }

    func fetchPhoto(from url: URL)