Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
NestedKey - ness
import UIKit
extension DictionaryLiteralConvertible where Key == String {
func nestedKey(key:String) -> AnyObject?{
let keys = key.componentsSeparatedByString(".")
let target:AnyObject? = self as? AnyObject
return keys.reduce(target) {x, y in
if x == nil { return x }
guard let curDict = x as? [String : AnyObject] else{
return nil
}
guard let next = curDict[y] else{
return nil
}
return next
}
}
}
let string = "a.b.c.d"
let dict = [ "a":["b":["c":["d":"Data"]]]]
let res = dict.nestedKey(string)
print(res)
//Optional(Data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment