Last active
August 15, 2020 00:45
-
-
Save simrandotdev/65d03ba86c1f25d81d67436b1c340f15 to your computer and use it in GitHub Desktop.
Final Code for video transformTo from a data object to Codable Models
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
| import UIKit | |
| let url = URL(string: "https://reqres.in/api/users/2")! | |
| URLSession.shared.dataTask(with: url) { (data, response, error) in | |
| if error != nil { | |
| print("Request failed with error: \(error?.localizedDescription)") | |
| return | |
| } | |
| guard let data = data else { | |
| print("Request failed: No Data found") | |
| return | |
| } | |
| let result = data.transformTo(to: Response.self) | |
| print(result!) | |
| }.resume() | |
| struct Response: Codable { | |
| var data: User | |
| } | |
| struct User: Codable { | |
| var id: Int | |
| var email: String | |
| var avatar: String | |
| } | |
| extension Data { | |
| func transformTo<T: Codable>(to type: T.Type) -> T? { | |
| do { | |
| let decoder = JSONDecoder() | |
| let response = try decoder.decode(type, from: self) | |
| return response | |
| } catch let error { | |
| print("Failed to convert JSON response: \(error.localizedDescription)") | |
| } | |
| return nil | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment