如何在swift中向字典添加新密钥?

时间:2016-12-02 08:46:44

标签: swift dictionary swift2 nsdictionary

如何在Swift中向Dictionary添加新密钥?我收到了一个错误:

  

此类不是密钥值编码兼容的密钥地址...

这是我的代码:

let user = [
     "id": id,
     "name" : name
]

if customer.address != nil {
    let address = [
         "street": customer.address.street,
         "zip": customer.address.zip,
    ]

    user.setValue(address, forKey: "address")
}

更新代码:

var user = [
            "id": customer.id,
            "name" : customer.fullName!,
            "position" : customer.position != nil ? customer.position! : ""
        ]

        if customer.address != nil {
            let address = [
                "street": customer.address!.street,
                "zip":   customer.address!.zip
            ]

            user["address"] = address
        }

2 个答案:

答案 0 :(得分:3)

问题是您正在尝试在字典中添加不同的类型值。如果要添加不同类型的值,请使用AnyAny可以代表任何类型的实例。

例如:

var user: [String: Any] = [
  "id": "dd",
  "name" : "ddd"
]

let address = ["street": "ss","zip": "124115"]

user["address"] = address

答案 1 :(得分:2)

只需将用户Dictionary decalration更改为var而不是常量,然后使用subscript通过密钥添加新值。

var user: [String: AnyObject] = [
    "id": id,
    "name" : name
]
user["address"] = address