如何在字典中插入具有值的新键

Lin*_*rld 27 iphone key nsmutabledictionary

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

我能够为字典中的现有键设置值,但我无法添加新的键值...

任何帮助,将不胜感激.

iPr*_*abu 50

使用NSMutableDictionary

NSMutableDictionary *yourMutableDictionary = [NSMutableDictionary alloc] init];
[yourMutableDictionary setObject:@"Value" forKey:@"your key"];
Run Code Online (Sandbox Code Playgroud)

Swift更新:

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

var yourMutableDictionary = NSMutableDictionary()
yourMutableDictionary.setObject("Value", forKey: "Key")
Run Code Online (Sandbox Code Playgroud)

但我建议你采用Swift Dictionary方式.

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"
Run Code Online (Sandbox Code Playgroud)