【发布时间】:2016-12-02 08:46:44
【问题描述】:
如何在 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
}
【问题讨论】:
-
你为什么首先使用字典?您应该为这样的数据创建数据模型。为您的数据创建一个具有您可以设置的属性的结构会更好(并且更容易......并且更安全)。 Swift 不是 JavaScript。别再这样对待它了。
-
@Fogmeister 我确实有数据模型,但这只是在我向服务器发送请求之前。
标签: swift dictionary swift2 nsdictionary