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]()
myDictionary["scores"] = l

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:


in python?

  • \$\begingroup\$ Can you provide more context? Where does the dictionary come from? Why do you use a dictionary instead of a custom type? \$\endgroup\$ – Martin R Nov 4 '18 at 18:47
  • \$\begingroup\$ 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. \$\endgroup\$ – 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.

I don't know about Python, but Swift doesn't check dictionary values at compile time.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.