Why I can not use SetValue for Dictionary?

2019-06-17 08:11发布

问题:

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.

回答1:

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)")


回答2:

I guess you need to use NSMutableDictionary.



回答3:

You can use NSMutableDictionary like this!

 var emptyDictionary = NSMutableDictionary()

 emptyDictionary.setObject("Your_Value", forKey:"Your_key")

 print(emptyDictionary)


标签: swift xcode6