Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can not use SetValue for Dictionary?

Tags:

swift

xcode6

Hello Everyone I am new in swift and In my app I declare a dictionary like this :

var imageDict : Dictionary<String, String> = [:]

and I want to set values for that dictionary like this :

imageDict.setValue(NSStringFromCGPoint(frame), forKey: NSString.stringWithString("/(tagValue)"));

But I got error like this :

Dictonary <String, String> does not have a member named 'setValue'

This question is from my previous question and can enybody explain my why I can not set value for that dictionar and can enybody tell me any other way to do that?

Thanks In advance.

like image 534
Dharmesh Kheni Avatar asked Oct 11 '14 10:10

Dharmesh Kheni


People also ask

How to set value in dictionary in Swift?

Adding to a Dictionary To add a new key-value to a dictionary, use subscript syntax by adding a new key contained within brackets [ ] after the name of a dictionary and a new value after the assignment operator ( = ).

Are Dictionary values optional Swift?

Because it is possible to request a key for which no value exists, a dictionary's subscript returns an optional value of the dictionary's value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key.


1 Answers

Swift dictionary does not have method like setValue:forKey:. Only NSMutableDictionary has such methods. If you wish to assign value for key in swift, you should use subscripting. Here is the correct way to do it, if you wish to do it with swift dictionary.

var imageDict:[String: String] = [:]

imageDict["\(tagValue)"] = NSStringFromCGRect(frame)

Or if you wish to use NSMutableDictionary then, it looks like this,

var imageDict = NSMutableDictionary()
imageDict.setObject(NSStringFromCGRect(frame), forKey: "\(tagValue)")
like image 100
Sandeep Avatar answered Nov 10 '22 10:11

Sandeep