您好我正在尝试给阵列中称为“插件”的alamofire参数...数组可以包含3个或X个项目。我试图使用FOR循环到广告词典到另一个另一组项目,但是...它只显示最后一个...它似乎覆盖了前一个。我尝试了所有我知道的东西......甚至尝试使用SwiftyJSON框架....但是alamofire只采用纯字典类型。
let itemsArr = ["Skirts", "Coat", "Shirt"]
let priceArr = ["7.00", "7.00", "2.90"]
let quantityArr = ["2", "5", "1"]
let personalInfo: [String : Any] = [
"phone" : phone,
"notes" : descNote
]
var para: [String: Any] = [
"pieces" : pieces,
"personal_info" : personalInfo,
"payment_method" : paymentMethod
]
for i in 0..<itemsArr.count {
let addons: [String: Any] = [
"name":itemsArr[i],
"price":priceArr[i],
"quantity":quantityArr[i]
]
print(addons)
para["addons"] = addons
}
我需要这样的东西
{
"pieces": 12,
"personal_info": {
"phone": "+420783199102",
"notes": "Plz be fast, I need to play Game of War"
},
"payment_method": "cod",
"addons": [
{
"name": "Select day Tue",
"price": 3.5,
"quantity": 1
},
{
"name": "Select day Thu",
"price": 3.5,
"quantity": 1
}
]
}
答案 0 :(得分:2)
你的问题是在循环中你用单个结果覆盖每次迭代的变量。这就是为什么只有最后一个留给你的原因。 你应该做的是:
//create an array to store the addons outside of the loop
var addons: [[String: Any]] = []
for i in 0..<itemsArr.count {
let addon: [String: Any] = [
"name":itemsArr[i],
"price":priceArr[i],
"quantity":quantityArr[i]
]
//append a single addon to our array prepared before the loop
addons.append(addon)
}
//once we gathered all addons, append results to `para` dictionary
para["addons"] = addons