首页 > 解决方案 > 如何为对象模型创建模型数据结构

问题描述

这是我必须从模型数据转换的对象数组。

 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?
}

但是当我打印这个结构时,它看起来不像我的数组对象。

标签: swiftdata-modeling

解决方案


基于 Jenny 的回答,您可以使您的结构符合CustomStringConvertible协议,并添加一个计算属性description

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。

然后,您可以为 Encodable 协议创建一个简单的扩展,让您可以将任何 Encodable 对象显示为“漂亮”的 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 语法而不是 Apple 用于显示数组和字典的语法,但概念是相同的......


推荐阅读