Search code examples
swiftdictionarykey

How to add/Update key/values in dict in swift?


func exercise() {

    
    var stockTickers: [String: String] = [
        "APPL" : "Apple Inc",
        "HOG": "Harley-Davidson Inc",
        "BOOM": "Dynamic Materials",
        "HEINY": "Heineken",
        "BEN": "Franklin Resources Inc"
    ]
    
    
    stockTickers["WORK"] = ["Slack Technologies Inc"]
    stockTickers["BOOM"] = ["DMC Global Inc"]


  
     
    print(stockTickers["WORK"]!)
    print(stockTickers["BOOM"]!)
}

Error: Cannot assign value of type '[String]' to subscript of type 'String'

I do not understand the error, I'm new to swift, can someone guide me through this and tell mw why I see this error.


Solution

  • Alexander explained what you need to do in abstract terms. (Voted)

    Specifically, change

    stockTickers["WORK"] = ["Slack Technologies Inc"]
    stockTickers["BOOM"] = ["DMC Global Inc"]
    

    To

    stockTickers["WORK"] = "Slack Technologies Inc"
    stockTickers["BOOM"] = "DMC Global Inc"
    

    The expression ["Slack Technologies Inc"] defines a String array containing a single string. That's not what you want. you defined a dictionary of type [String:String]

    If you wanted your dictionary to have String keys and values that contained arrays of strings, you'd have to change the way you declared your dictionary:

    var stockTickers: [String: [String]] = [
        "APPL" : ["Apple Inc"],
        "HOG": ["Harley-Davidson Inc"],
        "BOOM": ["Dynamic Materials"],
        "HEINY": ["Heineken"],
        "BEN": ["Franklin Resources Inc"]
    ]