Skip to content

Instantly share code, notes, and snippets.

@gauravkeshre
Last active January 13, 2019 19:50
Show Gist options
  • Save gauravkeshre/983caade6c6dd9a14c3ba949d2243f45 to your computer and use it in GitHub Desktop.
Save gauravkeshre/983caade6c6dd9a14c3ba949d2243f45 to your computer and use it in GitHub Desktop.
Dictionary Subscripts - Clever way to access data from dictionary

Dictionary custom subscript for cleaner access

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
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment