iT邦幫忙

2021 iThome 鐵人賽

DAY 22
0
Mobile Development

下班悠哉學 iOS 開發系列 第 22

【Day 22】 Swift 5.5 Async/await 新特性

由於今天比較晚才到家,所以可能內容會比較少一點。

另外今天在火車上看到github上面有幾個開源的 Github 分享列表。

有蠻多實用的東西

Open-Source iOS Apps

macOS status monitoring app written in SwiftUI.

github上面真的蠻多東西可以參考的。

現在進入正題

Async/await:

以前:

func fetchWeatherHistory(completion: @escaping ([Double]) -> Void) {
    // Complex networking code here; we'll just send back 100,000 random temperatures
    DispatchQueue.global().async {
        let results = (1...100_000).map { _ in Double.random(in: -10...30) }
        completion(results)
    }
}

func calculateAverageTemperature(for records: [Double], completion: @escaping (Double) -> Void) {
    // Sum our array then divide by the array size
    DispatchQueue.global().async {
        let total = records.reduce(0, +)
        let average = total / Double(records.count)
        completion(average)
    }
}

func upload(result: Double, completion: @escaping (String) -> Void) {
    // More complex networking code; we'll just send back "OK"
    DispatchQueue.global().async {
        completion("OK")
    }
}

以前調用的程式碼

fetchWeatherHistory { records in
    calculateAverageTemperature(for: records) { average in
        upload(result: average) { response in
            print("Server response: \(response)")
        }
    }
}

現在可以使用這樣的方式

func fetchWeatherHistory() async -> [Double] {
    (1...100_000).map { _ in Double.random(in: -10...30) }
}

func calculateAverageTemperature(for records: [Double]) async -> Double {
    let total = records.reduce(0, +)
    let average = total / Double(records.count)
    return average
}

func upload(result: Double) async -> String {
    "OK"
}

使用起來也更簡單

func processWeather() async {
    let records = await fetchWeatherHistory()
    let average = await calculateAverageTemperature(for: records)
    let response = await upload(result: average)
    print("Server response: \(response)")
}

上一篇
[day 21 ] SwiftUI Essentials - Building Lists and Navigation
下一篇
【Day23】SwiftUI Essentials - SwiftUI 基礎
系列文
下班悠哉學 iOS 開發30

尚未有邦友留言

立即登入留言