I would NOT redefine the standard subscript operator... better use your own:
extension Dictionary where Key == String, Value == Any {
subscript<T>(myValueForKey key: String) -> T? {
get { self[key] as? T }
set {
self[key] = newValue
}
}
}
Usage:
let foo: String? = configurationDict[myValueForKey: "bar"]
Note, the benefit at the use site is minimal, compare with normal:
let first = configurationDict[myValueForKey: "bar"] as! String?
let second = configurationDict[myValueForKey: "bar"] as? String
BTW - there's a difference between first and second here, sometimes you'd want the first (if you are sure that the value must be either absent or of a particular type), and sometimes you'd want the second (when the value could be of a different type and that's not an error situation).
I just realized that, in making an example, this is definitely different than I was doing in my actual code. I was actually running
if let foo: String = configurationDict["bar"] {}
which created the residual, non optional single statement when I was trying to simplify for the forums. However, I still did try both this and my original example and they both provide the same error. I think as @tera is suggesting, I can't replace the standard subscript.
That's totally fair! I thought it be an alternative to the standard, not redefine it. (aka, I thought it would use standard when no type is provided, but use the generic when explicitly defined)
My current solution was basically your alternative: stringForKey etc, but I'll see if the generic will work with my own label.