Last active
October 1, 2021 20:21
-
-
Save joaoduartemariucio/6033ee5d4942546f4037e962dcf73f62 to your computer and use it in GitHub Desktop.
Decodable with enum inside response
This file contains 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 Foundation | |
struct Response: Decodable { | |
let name: String | |
let note: String | |
let status: Status | |
} | |
enum Status: String, Decodable { | |
case observation = "OBSERVATION" | |
case progress = "PROGRESS" | |
case canceled = "CANCELED" | |
case completed = "COMPLETED" | |
} | |
let jsonString = "{\"name\": \"Joao\", \"note\": \"Change area light\", \"status\": \"COMPLETED\"}" | |
func decode<T: Decodable>(json: String) -> T? { | |
let jsonData = Data(jsonString.utf8) | |
do { | |
let decoded = try JSONDecoder().decode(T.self, from: jsonData) | |
return decoded | |
} catch { | |
print(error) | |
return nil | |
} | |
} | |
if let response: Response = decode(json: jsonString) { | |
print("Name:", response.name) | |
print("Note:", response.note) | |
print("Status:", response.status) | |
} | |
// OUTPUT | |
// Name: Joao | |
// Note: Change area light | |
// Status: completed | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment