Built-in func for not replacing a value in a Dictionary?

This topic was discussed at the beginning of the month.

Personally I haven't needed to worry about the performance yet, and just do

_ = someDict["someID", valueAddedIfNil: "someString"]
public extension Dictionary {
  subscript(
    key: Key,
    valueAddedIfNil value: @autoclosure() -> Value
  ) -> Value {
    mutating get {
      self[key]
      ?? { [value = value()] in
        self[key] = value
        return value
      } ()
    }
  }
}
3 Likes