Swift 中的 async await

Swift 中的 async await

async await

async-await 是在Swift 5.5 中的结构化并发变化的一部分,在swift中它主要用于允许多段代码同时运行。

async

async明确表明了一个方法执行异步操作,如下:

//定义了一个异步方法并且可以抛出异常
func fetchResult(_ value1: Int, _ value2: Int) async throws -> Int {
    
    
    
}

//async方法取代了以往我们使用的完成回调方法
func fetchResult(_ value1: Int, _ value2: Int, completion: (Result<Int, Error>) -> Void) {
    
    
    
}

await

await 是用于调用异步方法的关键字。awaitasync是一个组合,await始终等待async的回调。如下:

do {
    
    
    let ret = try await fetchResult(5, 6)
    print("Fetched result: \(ret).")
} catch {
    
    
    print("Fetched err: \(error).")
}

当然,直接使用也许会遇到这种错误 ‘async’ call in a function that does not support concurrency
这时可以使用

func useAsyneAwait() async {
    
    
    do {
    
    
        let ret = try await fetchResult(5, 6)
        print("Fetched result: \(ret).")
    } catch {
    
    
        print("Fetched err: \(error).")
    }
}

或者使用Task.init 从一个支持并发的新任务中调用异步方法

func useAsyneAwait() {
    
    
    Task {
    
    
        do {
    
    
            let ret = try await fetchResult(5, 6)
            print("Fetched result: \(ret).")
        } catch {
    
    
            print("Fetched err: \(error).")
        }
    }
}

最后组合

func fetchResult(_ value1: Int, _ value2: Int) async throws -> Int {
    
    
    let ret = value1 + value2
    //假设小于10就返回错误
    guard ret > 10 else {
    
    
        throw ResultError.failed
    }
    return ret
}

func fetchResult(_ value1: Int, _ value2: Int, completion: (Result<Int, Error>) -> Void) {
    
    
    
}

func useAsyneAwait() async {
    
    
    do {
    
    
        let ret = try await fetchResult(5, 6)
        print("Fetched result: \(ret).")
    } catch {
    
    
        print("Fetched err: \(error).")
    }
}

猜你喜欢

转载自blog.csdn.net/quanhaoH/article/details/127962469