为什么我不能将SetValue用于Dictionary?

时间:2021-05-31 21:44:51

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

大家好我是swift的新手,在我的应用程序中,我声明了这样的字典:

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?

这个问题来自我之前的问题,并且enybody可以解释为什么我不能为那个词典设定价值,并且enybody能告诉我任何其他方法吗?

Thanks In advance.

提前致谢。

3 个解决方案

#1


11  

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.

Swift字典没有像setValue这样的方法:forKey:。只有NSMutableDictionary有这样的方法。如果你想在swift中为key赋值,你应该使用下标。如果您希望使用swift词典,这是正确的方法。

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

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

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

或者,如果您希望使用NSMutableDictionary,它看起来像这样,

var imageDict = NSMutableDictionary()
imageDict.setObject(NSStringFromCGRect(frame), forKey: "\(tagValue)")

#2


0  

I guess you need to use NSMutableDictionary.

我想你需要使用NSMutableDictionary。

#3


-3  

You can use NSMutableDictionary like this!

您可以像这样使用NSMutableDictionary!

 var emptyDictionary = NSMutableDictionary()

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

 print(emptyDictionary)

#1


11  

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.

Swift字典没有像setValue这样的方法:forKey:。只有NSMutableDictionary有这样的方法。如果你想在swift中为key赋值,你应该使用下标。如果您希望使用swift词典,这是正确的方法。

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

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

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

或者,如果您希望使用NSMutableDictionary,它看起来像这样,

var imageDict = NSMutableDictionary()
imageDict.setObject(NSStringFromCGRect(frame), forKey: "\(tagValue)")

#2


0  

I guess you need to use NSMutableDictionary.

我想你需要使用NSMutableDictionary。

#3


-3  

You can use NSMutableDictionary like this!

您可以像这样使用NSMutableDictionary!

 var emptyDictionary = NSMutableDictionary()

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

 print(emptyDictionary)