Skip to content

Instantly share code, notes, and snippets.

@Nadohs
Last active December 30, 2015 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nadohs/d270fd7addf58a279ffd to your computer and use it in GitHub Desktop.
Save Nadohs/d270fd7addf58a279ffd to your computer and use it in GitHub Desktop.
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