我有简单的词典,定义如下:
var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
但后来我想在这个字典中添加一些元素,即3 : "efg"
但我不知道我怎么能执行这个我在网上搜索过很多的动作但没有什么可以帮助我。
任何人都可以告诉我如何将3 : "efg"
添加到现有字典中?
你正在使用NSDictionary
。除非你出于某种原因明确要求它是那种类型,否则我建议使用Swift字典。
您可以将Swift字典传递给任何期望NSDictionary
的函数而无需任何额外的工作,因为Dictionary<>
和NSDictionary
无缝地相互桥接。原生Swift方式的优点是字典使用泛型类型,因此如果您使用Int
作为键并使用String
作为值来定义它,则不能错误地使用不同类型的键和值。 (编译器代表您检查类型。)
根据我在代码中看到的内容,您的词典使用Int
作为键,String
作为值。要创建实例并在以后添加项目,您可以使用以下代码:
var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"
如果您以后需要将其分配给NSDictionary
类型的变量,只需进行显式转换:
let nsDict = dict as! NSDictionary
并且,如前所述,如果您想将它传递给期望NSDictionary
的函数,请按原样传递它,而不进行任何强制转换或转换。
var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "[email protected]"
print(dict)
到目前为止,我发现通过使用Swift的一个高阶函数(即“reduce”)将数据附加到字典的最佳方法。请按照以下代码段:
newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }
@Dharmesh在你的情况下,它会,
newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }
如果您在使用上述语法时发现任何问题,请通知我。
您可以使用另一个测试器类来设置字典值
variableValue["X"] = 3.14
在上面variableValue
是由另一个类创建的字典。你设置key:value
。
如果你想修改或更新NSDictionary,那么首先将它命名为NSMutableDictionary
let newdictionary = NSDictionary as NSMutableDictionary
然后简单地使用
newdictionary.setValue(value: AnyObject?, forKey: String)
你可以使用以下方式添加并将Dictionary
更改为NSMutableDictionary
dict["key"] = "value"
我知道这可能会很晚,但它可能对某人有用。因此,要将键值对添加到swift中的字典,可以使用updateValue(value:,forKey :)方法,如下所示:
var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
SWIFT 3 - XCODE 8.1
var dictionary = [Int:String]()
dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)
所以,你的字典包含:
字典[1:Hola,2:你好,3:Aloha]
如果你的词典是Int
到String
,你可以做到:
dict[3] = "efg"
如果您的意思是向字典的值添加元素,可能的解决方案:
var dict = Dictionary<String, Array<Int>>()
dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)
Swift 3+
将新值分配给Dictionary的示例。您需要将其声明为NSMutableDictionary:
var myDictionary: NSMutableDictionary = [:]
let newValue = 1
myDictionary["newKey"] = newValue
print(myDictionary)
在Swift中,如果您使用的是NSDictionary,则可以使用setValue
:
dict.setValue("value", forKey: "key")
鉴于以下两个词典:
var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]
以下是如何将所有项目从dic2添加到dic1:
dic2.map {
dic1[$0.0] = $0.1
}
干杯A.
Dict.updateValue
从字典更新现有密钥的值,或者如果密钥不存在则添加新的新键值对。
例-
var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")
结果-
▿ : 2 elements
- key : "userId"
- value : 866
▿ : 2 elements
- key : "otherNotes"
- value : "Hello"