Search code examples
swiftdictionaryswift-dictionary

Does the Swift standard Dictionary have a get-or-set function?


I found myself starting to want something like this:

extension Dictionary {
    mutating func get(_ key: Key, backup: Value) -> Value {
        if let stored = self[key] {
            return stored
        } else {
            self[key] = backup
            return backup
        }
    }
}

but in my experience, Swift leaves out things like this because it has an alternative (intended) way to do it. I haven't found such a way in documentation. Did I miss this function, or should I create it? Also, if they left it out and I shouldn't create it, why?


Solution

  • No it doesn't have a function like this. It is fine to create an extension in this circumstance.