Skip to content

Instantly share code, notes, and snippets.

@tylerjohnson10
Created June 13, 2017 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerjohnson10/6d63f89e18ef7838fd54223546336c4b to your computer and use it in GitHub Desktop.
Save tylerjohnson10/6d63f89e18ef7838fd54223546336c4b to your computer and use it in GitHub Desktop.
/* Functional Programming Approach */
// Conversion of Data to JSONObject
typealias Deserialize = (Data) -> (JSONObject?)
func JSON() -> Deserialize {
return { data in
do {
return try JSONObject(JSONSerialization.jsonObject(with: data, options: .allowFragments))
} catch {
return nil
}
}
}
// Conversion of JSONObject to Model
typealias Decode<T> = (JSONObject?) -> (T?)
// Helper for Decoding JSON
func decode<T>(valueForKey key: String, inDictionary dictionary: Dictionary<String, Any>?) -> T? {
guard let dictionary = dictionary, let object = dictionary[key] as? T else { return nil }
return object
}
// Creating a User from a JSONObject
func decodeUser() -> Decode<User> {
return { json in
guard let json = json, case .dictionary(let dictionary) = json else {
return nil
}
guard let firstName: String = decode(valueForKey: "FirstName", inDictionary: dictionary) else {
return nil
}
let avatarURL = decode(valueForKey: "AvatarURL", inDictionary: dictionary).flatMap { return URL(string: $0) }
return User(avatarURL: avatarURL, firstName: firstName)
}
}
// Example Usage
let userJSON: [String: Any] = [
"FirstName": "Tyler",
"AvatarURL": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/William_Howard_Taft_1909b.jpg/1200px-William_Howard_Taft_1909b.jpg"
]
let userData = try JSONSerialization.data(withJSONObject: userJSON, options: [])
let user = decodeUser()(JSON()(userData))
let imageData = try Data(contentsOf: user!.avatarURL!)
UIImageView(image: UIImage(data: imageData))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment