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)")
}
}
}
存在的問題是
回調函數很容易調用多次,或者忘記調用。
函數參數 @escaping (String) -> Void 看著也不直觀
“回調地獄”看起來也不美觀
在Swift 5.0 增加了Result 類型之前,返回錯誤也困難。
Swift 5.5 Async/await方式
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)")
}
Async / await 錯誤處理
swift 5.5 async 函數也可以像普通函數一樣拋出錯誤 async throws。
enum UserError: Error {
case invalidCount, dataTooLong
}
func fetchUsers(count: Int) async throws -> [String] {
if count > 3 {
// Don't attempt to fetch too many users
throw UserError.invalidCount
}
// Complex networking code here; we'll just send back up to `count` users
return Array(["Antoni", "Karamo", "Tan"].prefix(count))
}
func save(users: [String]) async throws -> String {
let savedUsers = users.joined(separator: ",")
if savedUsers.count > 32 {
throw UserError.dataTooLong
} else {
// Actual saving code would go here
return "Saved \(savedUsers)!"
}
}
使用也是類似
func updateUsers() async {
do {
let users = try await fetchUsers(count: 3)
let result = try await save(users: users)
print(result)
} catch {
print("Oops!")
}
}
函數加上async 并不會自動并行 concurrency
除非特殊處理,函數還是順序執行,并不會自動并行,更不會自動跑在在其他線程。
Xcode 13 playground中運行異步代碼
現在(2021-7-25)之前,暫時還沒有明顯優雅的方式在playground中執行async / await 代碼。參考這里,可以這樣執行
import Foundation
struct Main {
static func main() async {
await doSomething()
}
static func doSomething() async {
print("doSomething")
}
}
Task.detached {
await Main.main()
exit(EXIT_SUCCESS)
}
RunLoop.main.run()
Async / await: sequences
SE-0298提案為swift 引入了AsyncSequence
protocol,循環異步隊列。 使用AsyncSequence
使用和Sequence
幾乎一樣。需要遵循AsyncSequence
和AsyncIterator
,當然next()
方法需要時異步async
的,和Sequence
一樣,迭代結束確認返回nil
。
struct DoubleGenerator: AsyncSequence {
typealias Element = Int
struct AsyncIterator: AsyncIteratorProtocol {
var current = 1
mutating func next() async -> Int? {
defer { current &*= 2 }
if current < 0 {
return nil
} else {
return current
}
}
}
func makeAsyncIterator() -> AsyncIterator {
AsyncIterator()
}
}
運行也是常見的 for await
語法。
func printAllDoubles() async {
for await number in DoubleGenerator() {
print(number)
}
}
更高級的是,AsyncSequence
協議提供了一些常用的方法,像map()
, compactMap()
, allSatisfy()
等
func containsExactNumber() async {
let doubles = DoubleGenerator()
let match = await doubles.contains(16_777_216)
print(match)
}
read-only 屬性
SE-0310提案升級了swift的只讀屬性,讓其支持了async和throws。
enum FileError: Error {
case missing, unreadable
}
struct BundleFile {
let filename: String
var contents: String {
get async throws {
guard let url = Bundle.main.url(forResource: filename, withExtension: nil) else {
throw FileError.missing
}
do {
return try String(contentsOf: url)
} catch {
throw FileError.unreadable
}
}
}
}
使用自然像如下
func printHighScores() async throws {
let file = BundleFile(filename: "highscores")
try await print(file.contents)
}
Structured concurrency
SE-0304在async / await 和async sequence的基礎上為swift 引入了一整套的并發的執行,取消,監控的方法。 為了更好說明,我們先假設這兩個情況
enum LocationError: Error {
case unknown
}
func getWeatherReadings(for location: String) async throws -> [Double] {
switch location {
case "London":
return (1...100).map { _ in Double.random(in: 6...26) }
case "Rome":
return (1...100).map { _ in Double.random(in: 10...32) }
case "San Francisco":
return (1...100).map { _ in Double.random(in: 12...20) }
default:
throw LocationError.unknown
}
}
func fibonacci(of number: Int) -> Int {
var first = 0
var second = 1
for _ in 0..<number {
let previous = first
first = second
second = previous + first
}
return first
}
在swift的項目中,可以這么執行(如果在playground文件中,可以使用上文的方法)
@main
struct Main {
static func main() async throws {
let readings = try await getWeatherReadings(for: "London")
print("Readings are: \(readings)")
}
}
結構化并發,實際上是引入了兩個類型,Task
和TaskGroup
來,獨立或者協同地運行并發代碼。 簡單來說,你只要將異步代碼傳入Task
對象,就會立即在background 線程上運行,然后你用await
等待結果就好。
func printFibonacciSequence() async {
let task1 = Task { () -> [Int] in
var numbers = [Int]()
for i in 0..<50 {
let result = fibonacci(of: i)
numbers.append(result)
}
return numbers
}
let result1 = await task1.value
print("The first 50 numbers in the Fibonacci sequence are: \(result1)")
}
需要注意,代碼中明確指定了Task { () -> [Int] in
這樣,Swift就會知道task需要返回,而如果你的異步代碼比較簡單,可以像下面這樣寫:
let task1 = Task {
(0..<50).map(fibonacci)
}
再次,task會在創建之后立即運行,但是在斐波那契函數得到結果之后,,printFibonacciSequence()
函數會繼續運行在原來的線程。
task
參數屬于non-escaping 閉包
主要到task的函數參數中并沒有標注@escape
,因為task會立即執行傳入的函數,而不是存儲然后之后執行。因此,如果你在class
或者struct
中使用Task
,你不需要self
來獲取屬性和方法。
上述函數中,通過await task.value
來獲取task的值,如果你不關心task 返回的值,你也不需要存儲task。 對于會拋出錯誤的異步任務,從task的value
取值,也會觸發錯誤,因此仍然需要try await
。
func runMultipleCalculations() async throws {
let task1 = Task {
(0..<50).map(fibonacci)
}
let task2 = Task {
try await getWeatherReadings(for: "Rome")
}
let result1 = await task1.value
let result2 = try await task2.value
print("The first 50 numbers in the Fibonacci sequence are: \(result1)")
print("Rome weather readings are: \(result2)")
}
Swift為task內置了幾種優先級high
, default
,low
和background
。如果未指定,會默認設置為default
,當然你可以顯式指定Task(priority: .high)。當然如果你在Apple的平臺上,你會使用很熟悉的優先級,userInitiated
對應high
,utility
對應low
,當然你不能使用userInteractive
,它是為主線程保留的。 當然,Task也為我們提供了幾個靜態的方法。
-
Task.sleep()
會暫定當前任務一定時間(納秒,也就是1_000_000_000為1秒) -
Task.checkCancellation()
會檢查當前任務是否被cancel()取消,如果已經取消了,會拋出CancellationError
錯誤。 -
Task.yield()
會暫停當前任務一定時間,讓給其他等待的任務讓出點時間,這點在循環做一些繁重的任務會很有用。
func cancelSleepingTask() async {
let task = Task { () -> String in
print("Starting")
await Task.sleep(1_000_000_000)
try Task.checkCancellation()
return "Done"
}
// The task has started, but we'll cancel it while it sleeps
task.cancel()
do {
let result = try await task.value
print("Result: \(result)")
} catch {
print("Task was cancelled.")
}
}
上述代碼中,``Task.checkCancellation()會檢測到task已經被取消了,會立即跑出
CancellationError的錯誤,當然只有在嘗試
task.value取值的時候,才會拋出。
使用task.result
來獲取到Result
類型的值
你可以使用task.result
來獲取到Result
類型的值,上述代碼會返回Result<String, Error>
。當然你也就不需要try
來捕捉錯誤了。
對于復雜的任務,可以使用 task group來組織更多的task。
func printMessage() async {
let string = await withTaskGroup(of: String.self) { group -> String in
group.async { "Hello" }
group.async { "From" }
group.async { "A" }
group.async { "Task" }
group.async { "Group" }
var collected = [String]()
for await value in group {
collected.append(value)
}
return collected.joined(separator: " ")
}
print(string)
}
不要將withTaskGroup
里面的代碼復制到外面,編輯不會報錯,但是自然會有潛在的問題。 所有task group中的任務應該返回同樣的數據類型。復雜情況,你可能需要一個有associated值的enum來準確取值,當然你還可以使用async let 綁定的替代方案。 task group的值需要所有的task都完成,但是每個task執行完順序是不保證的。 你可以在task group中處理錯誤,或者你可以使用withThrowingTaskGroup()
把錯誤拋出,這樣也就需要try
的方式來取值。
func printAllWeatherReadings() async {
do {
print("Calculating average weather…")
let result = try await withThrowingTaskGroup(of: [Double].self) { group -> String in
group.async {
try await getWeatherReadings(for: "London")
}
group.async {
try await getWeatherReadings(for: "Rome")
}
group.async {
try await getWeatherReadings(for: "San Francisco")
}
// Convert our array of arrays into a single array of doubles
let allValues = try await group.reduce([], +)
// Calculate the mean average of all our doubles
let average = allValues.reduce(0, +) / Double(allValues.count)
return "Overall average temperature is \(average)"
}
print("Done! \(result)")
} catch {
print("Error calculating data.")
}
}
上述每個 async
任務,你可以簡化使用for location in ["London", "Rome", "San Francisco"] {
來調用。 task group 提供一個cancelAll()
的方法來取消所有的task。之后你仍然可以給group添加異步任務。當然,你可以使用asyncUnlessCancelled()
來跳過添加任務,如果group已經被取消—— 檢查Boolean的返回值類判斷group是否被取消。
async let 綁定
SE-0317引入了一種更簡易的語法async let
來創建和等待子任務。這個可以作為task group的替代方法,特別是你需要使用不同數據類型的異步任務時候。
struct UserData {
let username: String
let friends: [String]
let highScores: [Int]
}
func getUser() async -> String {
"Taylor Swift"
}
func getHighScores() async -> [Int] {
[42, 23, 16, 15, 8, 4]
}
func getFriends() async -> [String] {
["Eric", "Maeve", "Otis"]
}
可以使用如下簡單并發取值。
func printUserDetails() async {
async let username = getUser()
async let scores = getHighScores()
async let friends = getFriends()
let user = await UserData(name: username, friends: friends, highScores: scores)
print("Hello, my name is \(user.name), and I have \(user.friends.count) friends!")
}
你只能在async
的上下文中,使用async let
。
你只能在async
的上下文中,使用async let
。而且如果你不去使用await
取值,swift會在其作用于隱式等待。
綁定拋錯的異步方法的時候,你也不需要使用try
關鍵詞。只需要取值時候try await
。 更高級的是,我們可以遞歸的使用async let語法。
enum NumberError: Error {
case outOfRange
}
func fibonacci(of number: Int) async throws -> Int {
if number < 0 || number > 22 {
throw NumberError.outOfRange
}
if number < 2 { return number }
async let first = fibonacci(of: number - 2)
async let second = fibonacci(of: number - 1)
return try await first + second
}
Continuation函數(轉換回調異步為async函數)
SE-0300提供了把老的回調式異步函數轉換為async函數的方法。 例如,有如下的回調函數
func fetchLatestNews(completion: @escaping ([String]) -> Void) {
DispatchQueue.main.async {
completion(["Swift 5.5 release", "Apple acquires Apollo"])
}
}
swift 5.5之后,你不需要重寫你的所有代碼,你只需要使用withCheckedContinuation()
函數包裹就好。
func fetchLatestNews() async -> [String] {
await withCheckedContinuation { continuation in
fetchLatestNews { items in
continuation.resume(returning: items)
}
}
}
-
resume(returning:)
函數返回,你異步要返回的數據。 - 確保
resume(returning:)
函數只調用一次。在withCheckedContinuation()
函數中,swift會告警甚至會崩潰代碼,當然這會有性能損耗。 - 如果有更高性能要求,或者你確保你的代碼不會有問題,你可以使用``withUnsafeContinuation()
。
Actors
SE-0306引入了actor
,概念上和class
很相似,但是swfit確保了,actor中的變量在任意時間段內只會被一個線程獲取,這也就確保了actor在并發環境下的安全。 例如下面的代碼
class RiskyCollector {
var deck: Set<String>
init(deck: Set<String>) {
self.deck = deck
}
func send(card selected: String, to person: RiskyCollector) -> Bool {
guard deck.contains(selected) else { return false }
deck.remove(selected)
person.transfer(card: selected)
return true
}
func transfer(card: String) {
deck.insert(card)
}
}
在單線程的環境中都是OK的。但是在多線程的環境中,我們代碼就有了潛在的資源競爭風險,這也就導致了,當代碼并行運行時,代碼的執行結果會可能不同。 假設我們調用send(card:to:)
在同一時間調用多次,
- 第一個線程檢查card是否在deck,存在,繼續
- 第二個線程也檢查card是否在deck,存在,也繼續
- 第一個線程刪除了deck中的card然后轉移給了第二個人。
- 第二個線程嘗試刪除deck中的card,但是實際上已經不存在了,但是它還是把card轉移給了另一個人。
這樣就導致給一個人轉移了兩個卡片。絕對的麻煩。 Actor通過actor isolation隔離的方式解決這個問題:
- 只能從外部異步地讀取到actor的屬性和方法,
- 不能從外部寫存儲后的屬性
swift 內部通過隊列的方式避免資源競爭,因此應能不會很好。 對于上述的例子,我們可以改寫為:
actor SafeCollector {
var deck: Set<String>
init(deck: Set<String>) {
self.deck = deck
}
func send(card selected: String, to person: SafeCollector) async -> Bool {
guard deck.contains(selected) else { return false }
deck.remove(selected)
await person.transfer(card: selected)
return true
}
func transfer(card: String) {
deck.insert(card)
}
}
- 通過
actor
關鍵詞來創建一個Actor,這個是swift 新加的類型。 -
send()
方法被標為async
,因為它需要一定時間來完成card轉移。 -
transfer(card:)
并沒有標準為async
,但是我們仍然需要await
來調用,因為需要等待SafeCollector
actor能夠處理請求。
更細節來說,actor內部可以任意讀寫屬性和方法,但是和另一個actor交互的時候就必須使用異步的方式。這樣就保證了線程安全,而且更棒的事編譯后保證了這一點。 actor和class很像
- 都是引用類型,因此它們可以被用來分享狀態。
- 都有方法,屬性,構造器,和下標方法。
- 可以遵循協議和泛型
- 兩者靜態屬性和方法都是一樣的,因為它們沒有
self
,因此也就不需要隔離。
當然actor相比class有兩個最大的不同:
- Actor暫時不支持繼承,因此它們的構造器initializer就簡單多了——不需要convenience initializer,override,和
final
關鍵詞等。這個后續可能會改變。 - 所有的actor隱式的遵循了Actor的協議,其他的類型不能使用這個協議。
最好的actor
描述:“actors pass messages, not memory.”
actor不是直接訪問別的acotr內存,或者調用它們的方法,而是發送消息,讓swift runtime來安全處理數據。
Global actors
SE-0316引入了全局actor來隔離全局狀態避免數據競爭。 目前來說是引入了一個@MainActor
來標柱裝飾你的屬性和方法,讓其保證只在主線程運行。 對于app來說,UI更新就需要保證在主線程,以前的方式是使用DispatchQueue.main
。swift 5.5之后,就簡單了
class NewDataController {
@MainActor func save() {
print("Saving data…")
}
}
@MainActor
標柱之后,必須異步調用。
就像上文,這里實際上是actor
,因此,我們需要使用await
,async let
等來調用save()
@MainActor
底層是一個全局的actor
底層是MainActor
的結構體。其中有一個靜態的run()
方法來讓我們代碼在主線程中執行,而且也能夠返回執行結果。
Sendable協議和@Sendable閉包
SE-0302支持了“可傳送”的數據,也就是可以安全的向另一個線程傳送數據。也就是引入了新的Sendable
protocol和裝飾函數的@Sendable
屬性。 默認線程安全的有
- 所有Swift核心的值類型,
Bool
,Int
,String
等 - 包裹的值類型的可選值(Optional)。
- swift標準庫值類型的集合,例如,
Array<String>
,Dictionary<Int, String>
。 - 值類型的元組(Tuple)
- 元類型(Metatype),例如
String.self
上述的值,都遵循了Sendable
的協議。 而對于自定義的類型,如果滿足下面的情況
-
Actor
自動遵循Sendable
,因為actor內部異步的處理數據。 - 自定義的
struct
和enum
,如果它們只包含遵循Sendable
的值也會自動遵循Sendable
,這點和Codable
很像。 -
class
能夠遵循Sendable
,如果1. 繼承自NSObject
,或者2. 不繼承,而且所有的屬性是常量的且能夠遵循Sendable
,還有類得標注為final來防止將來的繼承。
Swift讓函數和閉包,標注@Sendable,來能夠并發調用。例如,Task的初始化函數標注了@Sendable,下面代碼能夠并發執行,因為其內捕獲的是常量。
func printScore() async {
let score = 1
Task { print(score) }
Task { print(score) }
}
如果score
是變量,就不能在task
內用了。
因為Task
會并發執行,如果是變量,就存在數據競爭了。
你可以在自己代碼標注@Sendable
,這樣也會強制上述的規則(值捕獲)。
func runLater(_ function: @escaping @Sendable () -> Void) -> Void {
DispatchQueue.global().asyncAfter(deadline: .now() + 3, execute: function)
}
鏈式調用中支持#if語法
SE-0308中Swift支持了在鏈式調用( postfix member expression)使用#if
的條件判斷表達式。這個乍看有點費解,其實是為了解決SwiftUI中根據條件添加view的修飾器。
Text("Welcome")
#if os(iOS)
.font(.largeTitle)
#else
.font(.headline)
#endif
支持嵌套調用
#if os(iOS)
.font(.largeTitle)
#if DEBUG
.foregroundColor(.red)
#endif
#else
.font(.headline)
#endif
當然,也不是非得在Swift UI中使用
let result = [1, 2, 3]
#if os(iOS)
.count
#else
.reduce(0, +)
#endif
print(result)
#if只能用在.
操作
只有.
操作才算是postfix member expression,所以#if不能用在 +
,[]
等操作上。
CGFloat 和 Double 隱式轉換
SE-0307改進為開發帶來了巨大的便利:Swift 能夠在大多數情況下隱式轉換CGFloat
和Double
。
let first: CGFloat = 42
let second: Double = 19
let result = first + second
print(result)
Swift會有限使用Double
,更棒的是,不需要重寫原來的代碼,列入,Swift UI中的scaleEffect()
仍然可以使用CGFloat
,swift 內部轉換為Double
。
Codable支持enum 關聯值
SE-0295升級了Swift Codable
,讓其能夠支持枚舉enum關聯值。之前只有遵循rawRepresentable
的enum才能使用Codable。
enum Weather: Codable {
case sun
case wind(speed: Int)
case rain(amount: Int, chance: Int)
}
現在能使用JSONEncoder的
let forecast: [Weather] = [
.sun,
.wind(speed: 10),
.sun,
.rain(amount: 5, chance: 50)
]
do {
let result = try JSONEncoder().encode(forecast)
let jsonString = String(decoding: result, as: UTF8.self)
print(jsonString)
} catch {
print("Encoding error: \(error.localizedDescription)")
}
// [{"sun":{}},{"wind":{"speed":10}},{"sun":{}},{"rain":{"amount":5,"chance":50}}]
函數中支持lazy關鍵詞
swift中lazy
關鍵詞能夠讓屬性延遲求值,現在swift 5.5之后,函數中也能使用lazy
關鍵詞了。
func printGreeting(to: String) -> String {
print("In printGreeting()")
return "Hello, \(to)"
}
func lazyTest() {
print("Before lazy")
lazy var greeting = printGreeting(to: "Paul")
print("After lazy")
print(greeting)
}
lazyTest()
property wrapper 可以裝飾到 function 和 closure 參數
SE-0293擴展了property wrapper讓其能夠裝飾到函數和閉包參數。 例如原來的函數
func setScore1(to score: Int) {
print("Setting score to \(score)")
}
setScore1(to: 50)
setScore1(to: -50)
setScore1(to: 500)
// Setting score to 50
// Setting score to -50
// Setting score to 500
使用property wrapper可以,用來固定score的參數。
@propertyWrapper
struct Clamped<T: Comparable> {
let wrappedValue: T
init(wrappedValue: T, range: ClosedRange<T>) {
self.wrappedValue = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
}
現在使用的
func setScore2(@Clamped(range: 0...100) to score: Int) {
print("Setting score to \(score)")
}
setScore2(to: 50)
setScore2(to: -50)
setScore2(to: 500)
// Setting score to 50
// Setting score to 0
// Setting score to 100
擴展泛型函數中協議靜態成員的查找
SE-0299 提升了Swift對泛型函數中協議靜態成員查找的能力。這點實際上也很能提升Swift UI的書寫的便利。 以前需要這么寫
Toggle("Example", isOn: .constant(true))
.toggleStyle(SwitchToggleStyle())
現在這么寫,就很方便
Toggle("Example", isOn: .constant(true))
.toggleStyle(.switch)
跟具體來說,假設我們有如下的協議和結構體
protocol Theme { }
struct LightTheme: Theme { }
struct DarkTheme: Theme { }
struct RainbowTheme: Theme { }
我們再定義一個Screen
協議,有一個theme的泛型函數,來設置主題。
protocol Screen { }
extension Screen {
func theme<T: Theme>(_ style: T) -> Screen {
print("Activating new theme!")
return self
}
}
現在我們有個 Screen
的結構體
struct HomeScreen: Screen { }
我們可以指定screen的主題為
let lightScreen = HomeScreen().theme(LightTheme())
現在Swift 5.5之后,我們可以在Theme
協議上加個靜態的屬性
extension Theme where Self == LightTheme {
static var light: LightTheme { .init() }
}
現在Swift 5.5 設置主題就簡單了
let lightTheme = HomeScreen().theme(.light)