Ensure value in a Dictionary

In many cases, I need to get the value from a dictionary given a key (usually a string). I have the following helper class:

public class ObjectCache<T> {
    private var cache = [String: T]()

    subscript(name: String) -> T? {
        get { return cache[name] }
        set { cache[name] = newValue }
    }

    func get(_ name: String, with builder: () -> T?) -> T? {
        var obj = cache[name]
        if obj == nil {
            obj = builder()
            cache[name] = obj
        }
        return obj
    }
}

This saves much keyboard typing and avoid common errors of oversight. Like below:

let serviceURL = self.urlCache.get(name) { return comp.url }!

Now my question is - Does Swift provide some builtin functionality like this? I just hope I did not re-event the wheel.

AFAIK, there is no such functionality.

In fact there are hundreds of situations where such helper classes are useful. That would probably be an overload to try to include them all.

Ensure value in a Dictionary
 
 
Q