Skip to content

Instantly share code, notes, and snippets.

@acotilla91
Created October 20, 2018 15:26
Show Gist options
  • Save acotilla91/3cddb99bf01a3375a6fea6bc283b4f96 to your computer and use it in GitHub Desktop.
Save acotilla91/3cddb99bf01a3375a6fea6bc283b4f96 to your computer and use it in GitHub Desktop.
import Foundation
func getStatusWithAnyCasting(jsonData: Data) -> Int {
guard
let json = try? JSONSerialization.jsonObject(with: jsonData, options: []),
let dict = json as? [String: Any],
let statusString = dict["status"] as? String,
!statusString.isEmpty,
let status = Int(statusString)
else {
return 0
}
return status
}
func getStatusWithAnyObjectCasting(jsonData: Data) -> Int {
guard
let json = try? JSONSerialization.jsonObject(with: jsonData, options: []),
let dict = json as? [String: AnyObject],
let statusString = dict["status"] as? String,
!statusString.isEmpty,
let status = Int(statusString)
else {
return 0
}
return status
}
let response = "{\"status\": \"200\"}"
let data = response.data(using: .utf8)!
let statusWithAny = getStatusWithAnyCasting(jsonData: data)
print("statusWithAny \(statusWithAny)")
let statusWithAnyObject = getStatusWithAnyObjectCasting(jsonData: data)
print("statusWithAnyObject \(statusWithAnyObject)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment