0

This is my object array that I have to convert from model data.

 let Product =  [
        [
            "id" : 23,
            "price" : 150,
            "quantity" : 10
        ],
        [
            "id" : 23,
            "price" : 150,
            "quantity" : 10
        ]
    ]

I was trying like this:

struct cartFood{
    var id: Int?
    var price: Int?
    var quantity: Int?
}

But when I print this struct it doesn't look like my array object.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
behtito
  • 3
  • 6
  • it's the array of array of strings – chandra1234 Aug 31 '18 at 12:49
  • yes.. this is array of array of strings – behtito Aug 31 '18 at 12:50
  • It isn't clear what you're asking. The first block of code you posted creates an array of dictionaries. The second block of code defines a struct, but doesn't create an instance of that struct. – Duncan C Aug 31 '18 at 12:51
  • Actually i want that if i print this struct it will look like my object data which i was given .. i am not to sure how to do – behtito Aug 31 '18 at 13:00
  • What do you mean "This is my object array that i have to convert from model data" and "my object data which i was given"? How are you given object data? In JSON? And are you saying that you want the data to be displayed in the format you posted at the top of your question? – Duncan C Aug 31 '18 at 13:36

2 Answers2

0

Is this closer to what you want?

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
  • 2,041
  • 13
  • 15
  • Actually i want that if i print this struct it will look like my object data which i was given – behtito Aug 31 '18 at 12:59
  • @behtito you need to make it conform to Encodable – Leo Dabus Aug 31 '18 at 13:00
  • if i print this.. its looks like [FoodaFood.cartFood(id: Optional(23), price: Optional(150), quantity: Optional(10)), FoodaFood.cartFood(id: Optional(23), price: Optional(150), quantity: Optional(10))] – behtito Aug 31 '18 at 13:13
0

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...

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • My answer is based on the OP's comment "Actually i want that if i print this struct it will look like my object data which i was given". I provided code that let's you print an array of `CartFood` structs and get the format shown in the original question. – Duncan C Aug 31 '18 at 13:15
  • Btw `let products = [(23,150,10),(23,150,10)].map(CartFood.init) ` – Leo Dabus Aug 31 '18 at 14:23
  • Cute trick, but I prefer named parameters to the initializer. Your version is too cryptic. – Duncan C Aug 31 '18 at 14:54
  • @LeoDabus What makes that legal? The initializer for a struct normally requires named parameters, so how is it that you can map an array of tuples to an array of `CartFood` structs? – Duncan C Aug 31 '18 at 14:57
  • kkk I don't know how it works under the hood but I think all you need it to match the number of elements and its types – Leo Dabus Aug 31 '18 at 15:24