繁体   English   中英

如何在 Swift 中将元素附加到字典中?

[英]How to append elements into a dictionary in Swift?

我有一个简单的字典,其定义如下:

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的函数,请按原样传递它,而无需进行任何强制转换或转换。

您可以使用以下方式添加并将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:你好,2:你好,3:阿罗哈]

如果你的字典是Int to String你可以简单地做:

dict[3] = "efg"

如果您的意思是将元素添加到字典的值中,则可能的解决方案是:

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

dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)

斯威夫特 3+

为字典分配新值的示例。 您需要将其声明为 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.forEach {
   dic1[$0.key] = $0.value
}

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"

[字符串:任何]

对于使用[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)
        }
    }
}
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")

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

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

输出将像

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

从 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)
var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "sample@email.com"
print(dict)

要添加新元素,只需设置:

listParameters["your parameter"] = value

到目前为止,我发现使用 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 }

如果您在使用上述语法时发现任何问题,请告诉我。

Swift 5 快乐编码

var tempDicData = NSMutableDictionary()

for temp in answerList {
    tempDicData.setValue("your value", forKey: "your key")
}

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

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

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

print(dict)

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

我添加了字典扩展

extension Dictionary {   
  func cloneWith(_ dict: [Key: Value]) -> [Key: Value] {
    var result = self
    dict.forEach { key, value in result[key] = value }
    return result  
  }
}

你可以像这样使用cloneWith

 newDictionary = dict.reduce([3 : "efg"]) { r, e in r.cloneWith(e) }

如果你想修改或更新 NSDictionary 那么首先将它类型转换为 NSMutableDictionary

let newdictionary = NSDictionary as NSMutableDictionary

然后简单地使用

 newdictionary.setValue(value: AnyObject?, forKey: String)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM