Swift 如何为对象模型创建模型数据结构
这是我必须从模型数据转换的对象数组Swift 如何为对象模型创建模型数据结构,swift,data-modeling,Swift,Data Modeling,这是我必须从模型数据转换的对象数组 let Product = [ [ "id" : 23, "price" : 150, "quantity" : 10 ], [ "id" : 23, "price" : 150, "quantity" : 10 ] ] 我试着这样做: st
let Product = [
[
"id" : 23,
"price" : 150,
"quantity" : 10
],
[
"id" : 23,
"price" : 150,
"quantity" : 10
]
]
我试着这样做:
struct cartFood{
var id: Int?
var price: Int?
var quantity: Int?
}
但是当我打印这个结构时,它看起来不像我的数组对象 这更接近你想要的吗
struct CartFood {
var id: Int
var price: Int
var quantity: Int
}
let products = [
CartFood(id: 23, price: 150, quantity: 10),
CartFood(id: 23, price: 150, quantity: 10)
]
基于Jenny的回答,您可以使结构符合
CustomStringConvertible
协议,并为描述添加计算属性:
struct CartFood: CustomStringConvertible {
var id: Int
var price: Int
var quantity: Int
var description: String {
return """
[
"id": \(id),
"price": \(price),
"quantity": \(quantity)
]
"""
}
}
let products = [
CartFood(id: 23, price: 150, quantity: 10),
CartFood(id: 23, price: 150, quantity: 10)
]
print("[\n",products.map {$0.description}.joined(separator: ",\n"), "\n]")
这将产生:
[
[
"id": 23,
"price": 150,
"quantity": 10
],
[
"id": 23,
"price": 150,
"quantity": 10
]
]
编辑:
或者,您可以使结构符合Codable
协议:
struct CartFood: Codable {
var id: Int
var price: Int
var quantity: Int
}
这意味着它可以轻松地转换为JSON或从JSON转换而来
然后,您可以为可编码协议创建一个简单的扩展,该扩展允许您将任何可编码对象显示为“漂亮”的JSON字符串:
extension Encodable {
var prettyJSON: String {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
guard let data = try? encoder.encode(self),
let output = String(data: data, encoding: .utf8)
else { return "Error converting \(self) to JSON string" }
return output
}
}
并按如下方式显示结构数组:
let products = [
CartFood(id: 23, price: 150, quantity: 10),
CartFood(id: 23, price: 150, quantity: 10)
]
print("products.prettyJSON =", products.prettyJSON)
这将产生:
products.prettyJSON = [
{
"id" : 23,
"price" : 150,
"quantity" : 10
},
{
"id" : 23,
"price" : 150,
"quantity" : 10
}
]
它使用JSON语法,而不是苹果用来显示数组和字典的语法,但概念是一样的…它是字符串数组的数组。。这是字符串数组。我不清楚你在问什么。您发布的第一个代码块创建了一个字典数组。第二段代码定义了一个结构,但没有创建该结构的实例。实际上,我希望如果我打印这个结构,它看起来就像我得到的对象数据。。我不知道该怎么做“这是我的对象数组,我必须从模型数据转换过来”和“我得到的对象数据”是什么意思?如何给对象数据?在JSON中?你是说你想让数据以你在问题顶部贴出的格式显示吗?实际上我想,如果我打印这个结构,它看起来就像我的对象数据given@behtito如果我打印这个,你需要使它符合Encodableif。。它看起来像[foodfood.cartFood(id:Optional(23),price:Optional(150),quantity:Optional(10)),foodfood.cartFood(id:Optional(23),price:Optional(150),quantity:Optional(10))]我的答案是基于OP的评论“实际上我希望如果我打印这个结构,它看起来像我得到的对象数据”。我提供的代码可以让您打印一组CartFood
结构,并获得原始问题中显示的格式。顺便说一句let products=[(23150,10),(23150,10)].map(CartFood.init)
可爱的技巧,但我更喜欢命名参数而不是初始值设定项。你的说法太隐晦了。@LeoDabus什么使它合法?结构的初始值设定项通常需要命名参数,那么如何将元组数组映射到CartFood
structs数组呢?kkk我不知道它是如何工作的,但我认为您需要它来匹配元素的数量和类型