Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

swift - Single object might have multiple types - decoding

I have the following struct, and try to decode the object as follows.

I am using Swift 4.3.

struct Classroom: Codable {
  let teacher: Teacher
  let id: Int
  let status: String?
}

let classes: Classroom = try clasroom.decodeObject()

However, status object has two different types either String or Dictionary. If it comes as a Dictionary, then I am only interested to assign the key to the status.

it works in the following case,

{"teacher": {"name": "Carolina"},"id": 20,"status": "Success"}

Wondering how to handle these type of scenarios?

{"id": 20, "teacher": {"name": "Carolina"},"status":{"Failure":"network is down"}}
question from:https://stackoverflow.com/questions/65926497/single-object-might-have-multiple-types-decoding

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...