4

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?

Ky -
  • 30,724
  • 51
  • 192
  • 308
  • 2
    Similar solutions here: [Swift Dictionary default value](http://stackoverflow.com/questions/32415188/swift-dictionary-default-value). – Martin R Dec 06 '16 at 17:53
  • You didn't miss out a function :) It's usually a good idea to create an extension or function of some kind (see my answer). – GJZ Dec 06 '16 at 18:07

1 Answers1

2

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

Jeremy Gurr
  • 1,613
  • 8
  • 11