This is more than common use case where we access some data from dictionary defined as [String: Any?].
Most of the time we are aware of the data type in advance we allpy force cast (not me) or optional binding to finally access the data.
Consider you have a user object coming in as a Dictionary<String: Any>
and you have to access the gender.
Now this gender
could have {0, 1, 2}, {"m", "f", "o"} or {"male", "female", "other"}
Similar thing can happen with boolean
, float
, etc
and you have to access this at many places.
How cool would it be if you could just do
let userGender = userDictionary[gender: "gender"]
let isUserActive = userDictionary[bool: "is_active"]
let weight = userDictionary[float: "wt"]
... so on
Well, have a look.
Note: This method (with enums) may be outdated in Swift 4.
*/
extension Dictionary where Key == String, Value == Any? {
subscript(float key: String) -> Float? {
get{
guard let val = self[key] else { return nil}
switch val {
case is Float: return val as? Float
case is Double: return Float(val as! Double)
case is Int: return Float(val as! Int)
case is CGFloat: return Float(val as! CGFloat)
case is String: return Float(val as! String)
default: return nil
}
}
set {
self[key] = newValue
}
}
}
/// For UUID
subscript(uuid key: String) -> UUID? {
get{
guard let val = self[key] else { return nil}
if let val = val as? UUID {
return val
}
if let strVal = val as? String,
let val = UUID(uuidString: strVal) {
return val
}
return nil
}
set {
self[key] = newValue
}
}