Declare status
as enum with associated values
enum Status : Decodable {
case success, failure(String)
init(from decoder : Decoder) throws
{
let container = try decoder.singleValueContainer()
do {
try container.decode(String.self)
self = .success
} catch {
let error = try container.decode(StatusError.self)
self = .failure(error.Failure)
}
}
}
and a helper struct
struct StatusError : Decodable {
let Failure : String
}
In Classroom
declare
let status: Status
And check the status
switch classroom.status {
case .success: print("OK")
case .failure(let message): print(message)
}
Of course the error handling can be more robust: Is the success
string really "Success"
? And you can decode the failure
type as [String:String]
and get the value for key Failure
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…