GaF
GaF

Reputation: 111

Access to key inside Dictionary get in Swift

Is it possible to access the key inside of a Dictionary get in Swift ?

The main idea is:

In this code

var _dict:[String:String]  = [:]

var dict:[String:String] {
    
    //get the key
    
    return _dict

}

_dict = ["key 1":"Value 1","key 2":"Value 2"]

print(dict["key 1"])

Access the key to check if the value exists, if it exists return the value if not generate the value for that key

Upvotes: 0

Views: 451

Answers (1)

New Dev
New Dev

Reputation: 49580

Did you know that Dictionary allows you to specify a default value in its subscript to avoid dealing with optional values. It works like so:

let dict = ["a": 1, "b": 2]
let c = dict["c", default: 3] 

print(c) // 3

but that doesn't change the dictionary - it's still only has "a" and "b" keys, which is the expected behavior.

I think what you're asking about is whether it's possible to mutate the dictionary with a default value. The answer is yes - you could create a subscript with a mutating get.

But it's the wrong thing to do!

You will effectively have a getter with side-effects, which is typically a bad practice.

In any case, this is how you could implement a subscript with a new parameter setDefault:

extension Dictionary {
   subscript(key: Key, setDefault defaultVal: @autoclosure () -> Value) -> Value {
      mutating get {
         if let val = self[key] { 
            return val 
         } else {
            let val = defaultVal()
            self[key] = val
            return val
         }
      }
   }
}
// dict needs to be a var now
var dict = ["a": 1, "b": 2]
let c = dict["c", setDefault: 3]

Now, this will mutate dict and it will be ["a": 1, "b": 2, "c": 3]

Upvotes: 3

Related Questions