Building on Jenny's answer, you can make your struct conform to the CustomStringConvertible
protocol, and add a computed property for 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]")
That outputs:
[
[
"id": 23,
"price": 150,
"quantity": 10
],
[
"id": 23,
"price": 150,
"quantity": 10
]
]
EDIT:
Alternatively, you can make your struct conform to the Codable
protocol:
struct CartFood: Codable {
var id: Int
var price: Int
var quantity: Int
}
That means it can be easily converted to/from JSON.
Then you can create a simple extension to the Encodable protocol that lets you display any Encodable object as a "pretty" JSON string:
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
}
}
And display your array of structs like this:
let products = [
CartFood(id: 23, price: 150, quantity: 10),
CartFood(id: 23, price: 150, quantity: 10)
]
print("products.prettyJSON =", products.prettyJSON)
That outputs:
products.prettyJSON = [
{
"id" : 23,
"price" : 150,
"quantity" : 10
},
{
"id" : 23,
"price" : 150,
"quantity" : 10
}
]
That uses JSON syntax rather than the syntax Apple uses to display arrays and dictionaries, but the concept is the same...