Skip to content

Instantly share code, notes, and snippets.

@joaoduartemariucio
Last active October 1, 2021 20:21
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 joaoduartemariucio/6033ee5d4942546f4037e962dcf73f62 to your computer and use it in GitHub Desktop.
Save joaoduartemariucio/6033ee5d4942546f4037e962dcf73f62 to your computer and use it in GitHub Desktop.
Decodable with enum inside response
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