gpt4 book ai didi

json - Swift MVVM 如何实现数组来建模

转载 作者:行者123 更新时间:2023-11-30 10:33:01 26 4
gpt4 key购买 nike

Rss Feed 模型中的数组以及如何解决此问题?我无法使用 MVVM 从 JSON 获取数据。

错误:无法将类型“[Product]”的值转换为预期参数类型“Product”

我很抱歉英语不好。

RSSFeed Model:

struct RSSFeed: Codable {
var title: String?
var description: String?
var icon: String?
var items: [Product]?
}

Product Model:

struct Product: Codable {
var id: String?
var title: String?
var specs: String?
var size: [String]?
var color: String?
var link: String?
var image: [String]?
var price: Price
}

Product View Model:

struct ProductViewModel {

private var product: Product!

init(product: Product) {
self.product = product
}

var id: String {
return product.id ?? ""
}

var title: String {
return product.title ?? ""
}

var specs: String {
return product.specs ?? ""
}

var size: [String] {
return product.size ?? [""]
}

var link: String {
return product.link ?? ""
}

var imageURL: [String] {
return product?.image ?? [""]
}

var price: String {
let rawValue = product.price.rawValue
let currency = product.price.currency

return "\(currency)\(rawValue)"
}
}

Product Provider (Problem is here)

class ProductProvider {

static let product = ProductProvider()

private init() {

}

func getProduct() -> [ProductViewModel] {
var rssFeed = RSSFeed()

let jsonFile = Bundle.main.path(forResource: "products", ofType: "json")

let data = try? Data(contentsOf: URL(fileURLWithPath: jsonFile!))
do {
rssFeed = try JSONDecoder().decode(RSSFeed.self, from: data!)

} catch let error {
print(error.localizedDescription)
}

if let product = (rssFeed.items) {
return ProductViewModel(product: product)
//Error: Cannot convert value of type '[Product]' to expected argument type 'Product'
}
return [ProductViewModel]()
}
}

如何获取 JSON 数据?

最佳答案

if 子句更改为

if let items = rssFeed.items {
return items.map {ProductViewModel(product: $0)}
}

由于一个 View 模型包含一种产品,因此您需要使用 Productitems 数组转换为 ProductViewModel 数组 map 函数

关于json - Swift MVVM 如何实现数组来建模,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58698937/

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