Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

iphone - How to insert a new key with value in dictionary

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use NSMutableDictionary

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

Update for Swift:

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

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

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...