如何在Swift 4中编写嵌套字典

时间:2019-01-21 09:53:28

标签: swift dictionary

所以我有这个json:

"transactions": [
        {
            "balance": "15000",
            "description": "Makan di indomaret",
            "date": "09-01-2019",
            "week": "1"
        },
        {
            "balance": "25000",
            "description": "Makan di alfamart",
            "date": "08-01-2019",
            "week": "1"
        }
    ]

我想用字典编写这个json结构。 这里的代码

var jsonData = [String : [[String : Any]]]() 

谢谢。

2 个答案:

答案 0 :(得分:0)

应该是

var jsonData = [[String : [[String : Any]]]()

因为键(“事务”)是字符串,并且其值(

[{
    "balance": "15000",
    "description": "Makan di indomaret",
    "date": "09-01-2019",
    "week": "1"
},
{
    "balance": "25000",
    "description": "Makan di alfamart",
    "date": "08-01-2019",
    "week": "1"
}]

是字符串数组:任意

答案 1 :(得分:0)

然后,您可以循环制作一个字典,稍后将其追加到arrayDictionary

let array = [[String:Any]]()

for item in data {
 let dictionary = [String:Any]()
 dictionary["object1"] = item.id
 dictionary["object2"] = item.name
 dictionary["object3"] = item.address

 array.append(dictionary)
}