Skip to content

Instantly share code, notes, and snippets.

@justAnotherDev
Created February 3, 2016 10:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justAnotherDev/40e1e8081ed6c7f9313c to your computer and use it in GitHub Desktop.
Save justAnotherDev/40e1e8081ed6c7f9313c to your computer and use it in GitHub Desktop.
Swift extensions for retrieving values from a JSON response
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