-
-
Save Nadohs/d270fd7addf58a279ffd to your computer and use it in GitHub Desktop.
NestedKey - ness
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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