0

i want to add more items to parameters, but for loop overwrite the exist data.

How can I add more item to parameters with loop?

var parameters: [String: Any] = [:]
let array = [1111,1112,1113,1114]
for product in array{
            parameters["line_items"] = [
            ["product_id": product, "quantity": 1]
        ]
        }

Thanks for your advice

2 Answers2

0

You need to assign an array of dictionaries to the line_items key. You can easily do that using map on products.

var parameters: [String: Any] = [:]
let products = [1111,1112,1113,1114]
parameters["line_items"] = products.map { product in ["product_id": product, "quantity": 1]}

print(parameters)
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
0

In general, you should create the array for the line_items key first, then assign it to the dictionary:

var lineItems = [Any]()
for product in array{
    lineItems.append(
        ["product_id": product, "quantity": 1]
    )
}
parameters["line_items"] = lineItems

But as Dávid Pásztor said, you can just do a map:

parameters["line_items"] = array.map {
    ["product_id": $0, "quantity": 1]
}

If you have a Codable struct that contains this data,

struct LineItems : Codable {
    let lineItems: [Product]
}

struct Product : Codable {
    let productId: Int
    let quantity: Int
}

I would also recommend that you use the DictionaryEncoder from this answer to create the entire dictionary.

let encoder = DictionaryEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let parameters = try encoder.encode(object)
Sweeper
  • 213,210
  • 22
  • 193
  • 313