如何在swift中将元素追加到字典中?

Dha*_*esh 191 nsdictionary swift

我有简单的词典,定义如下:

var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]
Run Code Online (Sandbox Code Playgroud)

但是后来我想在这本字典中添加一些元素 3 : "efg"

但我不知道我怎么能执行这个我在网上搜索过很多的动作但没有什么可以帮助我.

有谁能告诉我如何才能3 : "efg"加入现有的字典?

Ant*_*nio 221

你正在使用NSDictionary.除非你出于某种原因明确要求它是那种类型,否则我建议使用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"
Run Code Online (Sandbox Code Playgroud)

如果您以后需要将其分配给NSDictionary类型的变量,只需执行显式转换:

let nsDict = dict as! NSDictionary
Run Code Online (Sandbox Code Playgroud)

并且,如前所述,如果您想将其传递给期望的函数NSDictionary,请按原样传递它,而不进行任何强制转换或转换.


yas*_*h77 98

您可以使用以下方式添加并更改DictionaryNSMutableDictionary

dict["key"] = "value"
Run Code Online (Sandbox Code Playgroud)

  • 我收到一条错误消息,提示“无法分配给此表达式的结果” (2认同)
  • 它不适用于2.2+,dict只读表达式 (2认同)

Hea*_*Onn 64

我知道这可能会很晚,但它可能对某人有用.因此,要将键值对添加到swift中的字典,可以使用updateValue(value:,forKey :)方法,如下所示:

var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
Run Code Online (Sandbox Code Playgroud)


Cri*_*ora 44

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)
Run Code Online (Sandbox Code Playgroud)

所以,你的字典包含:

字典[1:Hola,2:你好,3:Aloha]

  • 这怎么比`dictionary [1] ="Hola"更好? (3认同)
  • 这只是另一种方法。一切都取决于您需要做什么!我的情况,这是最好的方法 (3认同)
  • 我知道你认为这更好; 这就是你发布它的原因.但我不知道这有多好.请告诉我这是怎么回事 (2认同)

Ale*_*dan 16

如果你的字典是IntString你可以简单地这样做:

dict[3] = "efg"
Run Code Online (Sandbox Code Playgroud)

如果您的意思是向字典的添加元素,可能的解决方案:

var dict = Dictionary<String, Array<Int>>()

dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)
Run Code Online (Sandbox Code Playgroud)


Das*_*oga 16

Swift 3+

将新值分配给Dictionary的示例.您需要将其声明为NSMutableDictionary:

var myDictionary: NSMutableDictionary = [:]
let newValue = 1
myDictionary["newKey"] = newValue
print(myDictionary)
Run Code Online (Sandbox Code Playgroud)


小智 12

在Swift中,如果您使用的是NSDictionary,则可以使用setValue:

dict.setValue("value", forKey: "key")
Run Code Online (Sandbox Code Playgroud)


小智 11

鉴于以下两个词典:

var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]
Run Code Online (Sandbox Code Playgroud)

以下是如何将所有项目从dic2添加到dic1:

dic2.map {
   dic1[$0.0] = $0.1
}
Run Code Online (Sandbox Code Playgroud)

干杯A.

  • 最好使用`.forEach`而不是`.map`,因为我们不需要任何返回映射数组 (9认同)

小智 10

要添加新元素只需设置:

listParameters["your parameter"] = value
Run Code Online (Sandbox Code Playgroud)


Dha*_*ena 10

[字符串:任何]

对于使用[String:Any]而不是Dictionary下面的研究员是扩展名

extension Dictionary where Key == String, Value == Any {
    
    mutating func append(anotherDict:[String:Any]) {
        for (key, value) in anotherDict {
            self.updateValue(value, forKey: key)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

Dict.updateValue 从字典更新现有密钥的值,或者如果密钥不存在则添加新的新键值对.

例-

var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")
Run Code Online (Sandbox Code Playgroud)

结果-

?  : 2 elements
    - key : "userId"
    - value : 866
?  : 2 elements
    - key : "otherNotes"
    - value : "Hello"
Run Code Online (Sandbox Code Playgroud)


Lal*_*dav 8

For whoever reading this for swift 5.1+

  // 1. Using updateValue to update the given key or add new if doesn't exist


    var dictionary = [Int:String]()    
    dictionary.updateValue("egf", forKey: 3)



 // 2. Using a dictionary[key]

    var dictionary = [Int:String]()    
    dictionary[key] = "value"



 // 3. Using subscript and mutating append for the value

    var dictionary = [Int:[String]]()

    dictionary[key, default: ["val"]].append("value")
Run Code Online (Sandbox Code Playgroud)


小智 7

没有将数据附加到字典中的功能。您只需根据现有字典中的新键分配值。它会自动为字典添加值。

var param  = ["Name":"Aloha","user" : "Aloha 2"]
param["questions"] = "Are you mine?"
print(param)
Run Code Online (Sandbox Code Playgroud)

输出将像

[“姓名”:“阿罗哈”,“用户”:“阿罗哈 2”,“问题”:“你是我的吗?”]


Lor*_*bis 5

从 Swift 5 开始,以下代码集合有效。

 // main dict to start with
 var myDict : Dictionary = [ 1 : "abc", 2 : "cde"]

 // dict(s) to be added to main dict
 let myDictToMergeWith : Dictionary = [ 5 : "l m n"]
 let myDictUpdated : Dictionary = [ 5 : "lmn"]
 let myDictToBeMapped : Dictionary = [ 6 : "opq"]

 myDict[3]="fgh"
 myDict.updateValue("ijk", forKey: 4)

 myDict.merge(myDictToMergeWith){(current, _) in current}
 print(myDict)

 myDict.merge(myDictUpdated){(_, new) in new}
 print(myDict)

 myDictToBeMapped.map {
     myDict[$0.0] = $0.1
 }
 print(myDict)
Run Code Online (Sandbox Code Playgroud)


Har*_*ain 5

要将新的键值对附加到字典中,您只需设置键的值即可。例如。

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]
 
// Add a new key with a value

dict["email"] = "john.doe@email.com"

print(dict)
Run Code Online (Sandbox Code Playgroud)

输出->["surname": "Doe", "name": "John", "email": "john.doe@email.com"]