Created
February 3, 2016 10:26
-
-
Save justAnotherDev/40e1e8081ed6c7f9313c to your computer and use it in GitHub Desktop.
Swift extensions for retrieving values from a JSON response
This file contains hidden or 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
extension Dictionary where Key: StringLiteralConvertible, Value:AnyObject { | |
subscript(keysAndIndexes: AnyObject ...) -> AnyObject? { | |
guard let jsonObject = self as? AnyObject else { fatalError("\(self) is not a json dictionary") } | |
return _extractValueFrom(keysAndIndexes, from: jsonObject) | |
} | |
} | |
extension Array where Element:AnyObject { | |
subscript(keysAndIndexes: AnyObject ...) -> AnyObject? { | |
return _extractValueFrom(keysAndIndexes, from: self) | |
} | |
} | |
private func _extractValueFrom(keysAndIndexes: [AnyObject], from: AnyObject) -> AnyObject? { | |
var previousValue: AnyObject? = from | |
for keyOrIndex in keysAndIndexes { | |
if let key = keyOrIndex as? String, dict = previousValue as? Dictionary<String, AnyObject> { | |
// a key (String) was passed and previous value is a dictionary | |
previousValue = dict[key] | |
} else if let index = keyOrIndex as? Int, array = previousValue as? Array<AnyObject> { | |
// an index (Int) was passed and previous value is an array | |
previousValue = array[index] | |
} else { | |
return nil | |
} | |
} | |
return previousValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment