How to append elements into a dictionary in Swift?

后端 未结 19 1928
旧时难觅i
旧时难觅i 2020-11-28 23:31

I have a simple Dictionary which is defined like:

var dict : NSDictionary = [ 1 : \"abc\", 2 : \"cde\"]

Now I want to add an element into t

相关标签:
19条回答
  • 2020-11-29 00:04

    Dict.updateValue updates value for existing key from dictionary or adds new new key-value pair if key does not exists.

    Example-

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

    Result-

    ▿  : 2 elements
        - key : "userId"
        - value : 866
    ▿  : 2 elements
        - key : "otherNotes"
        - value : "Hello"
    
    0 讨论(0)
  • 2020-11-29 00:04

    Swift 5 happy coding

    var tempDicData = NSMutableDictionary()
    
    for temp in answerList {
        tempDicData.setValue("your value", forKey: "your key")
    }
    
    0 讨论(0)
  • 2020-11-29 00:06

    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)
    

    So, your dictionary contains:

    dictionary[1: Hola, 2: Hello, 3: Aloha]

    0 讨论(0)
  • 2020-11-29 00:08

    If your dictionary is Int to String you can do simply:

    dict[3] = "efg"
    

    If you mean adding elements to the value of the dictionary a possible solution:

    var dict = Dictionary<String, Array<Int>>()
    
    dict["key"]! += [1]
    dict["key"]!.append(1)
    dict["key"]?.append(1)
    
    0 讨论(0)
  • 2020-11-29 00:10
    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")
    
    0 讨论(0)
  • 2020-11-29 00:12

    In Swift, if you are using NSDictionary, you can use setValue:

    dict.setValue("value", forKey: "key")
    
    0 讨论(0)
提交回复
热议问题