swift - 如何在 swift 中向字典添加新键?

标签 swift dictionary swift2 nsdictionary

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

This class is not key value coding-compliant for the key address...

这是我的代码:

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
        }

最佳答案

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

例如:

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

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

user["address"] = address

关于swift - 如何在 swift 中向字典添加新键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40928013/

相关文章:

ios - 对包含 NSDate 对象的 NSArray 进行排序

ios - 如何用动画结束 UILongPressGestureRecognizer?

python - 将列表与字典进行比较 - 如果值与列表匹配则返回键

c# - 将 Json 转换为字典 C#

c# - 字典对象错误 : The name 'LotMaterialList' does not exist in the current context

ios - UIScrollView 内的 UITableView - 单元格不可单击

xcode - 如何使用变量来构造命令

嵌套结构类型的 Swift 数组 (count, repeatedValue)

swift - 连续的单元测试失败,尽管它们单独成功

swift - 设置数据源和委托(delegate)会使 UITableView 的应用程序崩溃