Swift 5.5 使用async await actor

新旧方法对比

Swift 5.5添加了async await 用于支持异步编程,使用起来确实比之前方便多了。新的方法系统版本最低要求是iOS 15.

    // 使用闭包
    func mockRequest(_ request: URLRequest, complete: @escaping (User?) -> Void) {
        URLSession.shared.dataTask(with: request) { data, _, _ in
            guard let data = data else { return }
            do {
                let user = try JSONDecoder().decode(User.self, from: data)
                complete(user)
            } catch {
                print(error)
                complete(nil)
            }
        }.resume()
    }
    // 使用async await
    func mockRequest(_ request: URLRequest) async -> User? {
        do {
            let (data, _) = try await URLSession.shared.data(for: request)
            let user = try JSONDecoder().decode(User.self, from: data)
            return user
        } catch {
            print(error)
            return nil
        }
    }

在同步方法内调用async方法的时候,需要使用Task,在同为async方法内可以直接调用.

        Task {
            let user = await mockRequest(request)
            print(user)
        }

使用actor定义对象结构

actor DataDownloader {
    private var cache: [URL: Data] = [:]

    func download(from url: URL) async throws -> Data {
        if let data = cache[url] {
            return data
        }

        let (data, _) = try await URLSession.shared.data(from: url)
        cache[url] = data
        return data
    }

    func download(request: URLRequest) async throws -> Data? {
        guard let url = request.url else { return nil }
        if let data = cache[url] {
            return data
        }

        let (data, _) = try await URLSession.shared.data(for: request)
        cache[url] = data
        return data
    }
}

流行的网络框架Alamofire就是使用的之前的API编写的

发现一个使用async await actor编写的新的框架Get,试用了一下,感觉不错

Get可以有效的减少代码量

github仓库地址 https://github.com/SunZhiC/UseAsync-Await-Actor

References

https://kean.blog/post/new-api-client

你可能感兴趣的:(Swift 5.5 使用async await actor)