# Swift append an array when it's been declared as Any

I'm learning Swift and I have a following problem: I create a dictionary containing some data, one of which is stored as an array. I want make an operation on this array to add some info. Currently I have managed to achieve this by writing this code:

var myDictionary = [String: Any]()

myDictionary = [
"name": "Wiktor",
"age": 25,
"scores": [1, 2, 3, 4, 5, 6],
]

var l = myDictionary["scores"] as? [Int] ?? [Int]()
l.append(100)
myDictionary["scores"] = l
print("\(myDictionary["scores"]!)")


This works, meaning an array with value 100 is printed out, but this solution seems a little bit over engineered to me. Can I do it easier, more like:

myDictionary["scores"].append(100)


in python?

• Can you provide more context? Where does the dictionary come from? Why do you use a dictionary instead of a custom type? – Martin R Nov 4 '18 at 18:47
• It's only for educational purpose. I'm going through Apple's tutorial and wanted to understand better how arrays and dictionaries work, so I've come up with this example. – gonczor Nov 4 '18 at 18:50

Since myDictionary values are declared as Any, you could have anything (or even nothing) assigned at "scores", so you need to safe-cast the value in to a variable first and then reassign it.