gpt4 book ai didi

swift - 异步等待 "Type of expression is ambiguous without more context"错误 - 在 swiftUI 中

转载 作者:行者123 更新时间:2023-12-04 14:01:32 25 4
gpt4 key购买 nike

在这一行 DispatchQueue.main.async我收到此错误:

Type of expression is ambiguous without more context

import Foundation

class ProductListViewModel: ObservableObject {
@Published var productList = [Product]()
let webService = WebService()

func downloadData(url: URL) async {

do {
let product = try await webService.getData(url: url)
DispatchQueue.main.async {
self.productList = product.map(ProductViewModel.init)
}
} catch {
print("error")
}
}
}

struct ProductViewModel {

let productModel: Product
var id: Int {
productModel.id
}
var title: String {
productModel.title
}
var price: Double {
productModel.price
}
var description: String {
productModel.description
}
var category: Category {
productModel.category
}
var imageUrl: String {
productModel.imageUrl
}
var rating: Rating {
productModel.rating
}
}

struct WebService {

func getData(url: URL) async throws -> [Product] {
let (data, _) = try await URLSession.shared.data(from: url)
let product = try? JSONDecoder().decode([Product].self, from: data)
return product ?? []
}
}

最佳答案

错误(无可否认,这里是非描述性且无益的)是因为您试图设置 [ProductViewModel] (这是您的 map 返回的)到 productList这是类型 [Product] .ProductViewModel这里似乎没有目的——它只是产品的相同包装。您可以在 do 中更改您的代码阻止这个:

let products = try await webService.getData(url: url)
DispatchQueue.main.async {
self.productList = products
}
要进一步重构,您应该注释您的 ProductListViewModel@MainActor确保在主队列上设置其属性,然后您可以摆脱 DispatchQueue.main.async来电——新 async/await API 与 DispatchQueue 不能很好地混合反之亦然。
@MainActor class ProductListViewModel: ObservableObject {
@Published var productList = [Product]()
let webService = WebService()

func downloadData(url: URL) async {
do {
let products = try await webService.getData(url: url)
self.productList = products
} catch {
print("error")
}
}
}

关于swift - 异步等待 "Type of expression is ambiguous without more context"错误 - 在 swiftUI 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69915494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com