Swift-使用字典将数据传递给参数

时间:2019-05-15 06:15:52

标签: arrays swift dictionary

我正在尝试在参数中传递一些数据以发送到服务器。但是我在构建参数方面面临一些困难。

我试图遍历数组以添加包含手机和名称的字典,但是由于它仅返回数组的第一个元素,因此我不确定如何正确构建字典。我不知道如何将所有内容附加到数组中。

     var parameters: [String: Any] = ["invitations": [
            ["mobile": "1234567",
            "name": "John1"]
            ]
        ]

        for (item1, item2) in zip(arrName, arrNumber){
            parameters = ["invitations": [
                "mobile" : "\(item2)",
                "name" : "\(item1)"]
            ]

        }

这是我要在参数中构建的JSON。

{
    "invitations": [ 
        {
          "mobile": "1234456",
          "name": "Paul"
        },
        {
          "mobile": "1234456",
          "name": "Paul1"
        },
        {
          "mobile": "1234456",
          "name": "Paul2"
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

let arr = zip(arrNumber,arrName).map { ["mobile":$0,"name":$1] }
var parameters: [String: Any] = ["invitations": arr]
print(parameters)//["invitations": [["name": "Paul", "mobile": "1234456"], ["name": "Paul1", "mobile": "1234456"], ["name": "Paul2", "mobile": "1234456"]]]
do {
    let json = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
    let convertedString = String(data: json, encoding: .utf8) 
    print(convertedString)

} catch let error {
    print(error.localizedDescription)
}
  

{“邀请”:[       {         “ name”:“ Paul”,         “ mobile”:“ 1234456”       },       {         “名称”:“ Paul1”,         “ mobile”:“ 1234456”       },       {         “名称”:“ Paul2”,         “ mobile”:“ 1234456”       }]}