Swift: Access value with keys in chain

In Objective C, it is pretty simple to access any value no matter how deep it is in a NSDictionary. If there is any key not found in the chain, it simply returns null.

NSDictionary *nsDic = @{@"apple": @{@"color": @"green"}, @"pear": @{@"color": @"yellow"}};  
nsDic[@"pear"][@"color"] //=> "yellow"  
nsDic[@"orange"][@"color"] //=> null  

While because of Optional, it becomes a bit tricky to do that in Swift's Dictionary struct or NSDictionary class. You will need to add "?" to allow a parent level to be nil, in order to access its children's value. For example:

var dic:Dictionary = ["apple": ["color": "green"], "pear": ["color": "yellow"]]  
dic["apple"]["color"] // => Compile error  
dic["apple"]?["color"] // => "green"  

Or if the target is NSDictionary, you can simple do with "valueForKeyPath":

var nsDic:NSDictionary = ["apple": ["color": "green"], "pear": ["color": "yellow"]]  
nsDic.valueForKeyPath("apple.color") // => "green"  
nsDic.valueForKeyPath("orange.color") // => nil  

Since Swift 1.2, "if let" has been introduced to Dictionary to make condition in Dictionary really easy. It's not just combining two steps/lines into one, as nil can't be used as a boolean in Swift condition.

var fruit:Dictionary = ["type": dic]  
if let color = fruit["type"]?["apple"]?["color"] {  
    println("the fruit color is \(color)")
} else {
    println("invaid keys")