0

How do you append to an array thats being used as a value in a dictionary on Swift?

Currently I have got:

var excercises = Dictionary<String, Array<String>>()

excercises["key"]!.append("value")

It doesn't give a syntax error, though:

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1004bc448)

What I'm trying to ask is, how do you use a dictionary with array to append/remove?

Sasuke
  • 13
  • 5
  • Please see https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu – rmaddy Oct 01 '17 at 03:54
  • I'm not so much interested in the error but as to how to use the dictionary itself – Sasuke Oct 01 '17 at 04:04

2 Answers2

0

I have written your problem in Swift playground and no errors have occurred. You must reference a "Key" instead of the word "Key" as it is trying to find an array in your dictionary which has currently none.

Code-

var str = "Hello, playground"
var myDictionary: [String: [String]] = ["Hello": ["One", "Two"],"World": ["Three", "Four"]]
myDictionary["World"]!.append("Five")
Hoovin Shmoovin
  • 161
  • 2
  • 13
  • You don't get an error because you are populating the dictionary before trying to append the array. The OP gets an error because they are trying to append to a non-existent array. – rmaddy Oct 01 '17 at 15:39
0

I guess you are looking for updating value in a dictionary :

    var dict = [String: [String]]()
    var array = ["abc","def"]

    dict["key"] = array
    array.append("ghi")

    dict.updateValue(array, forKey: "key")
Arnav
  • 668
  • 6
  • 14