所以我在這里有一個在型別async上定義的方法。actor我遇到的問題是根本people沒有發生突變;主要是由于我所理解的并發問題。據我所知,完成處理程式是在同一個執行緒上同時執行的,因此不能 mutate people。
盡管如此,我在這方面的知識還很模糊,所以任何解決它的建議,也許更好地解釋為什么會發生這種情況會很棒!我已經想到了一些事情,但我對并發仍然很陌生。
func getAllPeople() async -> [PersonModelProtocol] {
let decoder = JSONDecoder()
var people: [Person] = []
let dataTask = session.dataTask(with: request!) { data, response, error in
do {
let newPeople = try! decoder.decode([Person].self, from: data!)
people = newPeople
} catch {
print(error)
}
}
dataTask.resume()
return people
}
uj5u.com熱心網友回復:
如果您確實想使用async/await,則必須使用適當的 API。
func getAllPeople() async throws -> [Person] {
let (data, _ ) = try await session.data(for: request!)
return try JSONDecoder().decode([Person].self, from: data)
}
在同步背景關系中,無論如何您都不return能從完成處理程式中獲取資料。
uj5u.com熱心網友回復:
vadian 是對的,但現在它被更好地表達為計算屬性。
var allPeople: [PersonModelProtocol] {
get async throws {
try JSONDecoder().decode(
[Person].self,
from: await session.data(for: request!).0
)
}
}
而且,您的代碼確實 mutate people,但在它被變異之前回傳它的空值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448908.html
