如何在字典中插入带有值的新键 [英] How to insert a new key with value in dictionary

查看:135
本文介绍了如何在字典中插入带有值的新键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在现有字典中插入一个具有相应值的键...

I want to insert a key with a corresponding value in an existing dictionary...

我可以为字典中的现有键设置值,但是我我无法添加新的密钥值...

I am able to set values for existing keys in the dictionary, but I am not able to add a new key value...

任何帮助都将不胜感激。

Any help would be appreciated.

推荐答案

使用NSMutableDictionary

Use NSMutableDictionary

NSMutableDictionary *yourMutableDictionary = [NSMutableDictionary alloc] init];
[yourMutableDictionary setObject:@"Value" forKey:@"your key"];

Swift更新:

以下是上述代码的确切swift副本

The following is the exact swift replica for the code mentioned above

var yourMutableDictionary = NSMutableDictionary()
yourMutableDictionary.setObject("Value", forKey: "Key")

但我建议你使用Swift Dictionary方式。

But i would suggest you to go with Swift Dictionary way.

var yourMutableDictionary = [String: AnyObject]() //Open close bracket represents initialization

//The reason for AnyObject is a dictionary's value can be String or
//Array or Dictionary so it is generically written as AnyObject

yourMutableDictionary["Key"] = "Value"

这篇关于如何在字典中插入带有值的新键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆