Search code examples
swiftswift4foundation

Idiomatic way to construct a default value for a dictionary key in swift and set it


I'm looking for the idiomatic swifty way to create and then set values for collections contained in a dictionary for non existing keys

My code is quite tedious with this type of code scattered around:

var myDict = Dictionary<String,Array<String>>()
var arr = myDict["key"]
if arr = nil {
  arr = Array<String>()
  myDict["key"] = arr
}

... do something with arr...

is there something that handles this?


Solution

  • There is no way to set a default value for a Dictionary, but you can specify a default value when looking up a dictionary value:

    var arr = myDict["key", default: []]
    

    default provides a default value if the key is not found. In this case, you can use [] which Swift will infer to be an empty array of type [String].