问题
I am new to swift and codable too. I have below codable. I am getting all response of API in "RecentResult". I want to check "data" is empty or not. How do I check it?
struct RecentResult: Codable
{
let input: Input
let commandResult: CommandResultClass
}
struct CommandResultClass: Codable {
let success: Int
let message: String
let data: DataClass
}
struct DataClass: Codable {
let recentCount: String
enum CodingKeys: String, CodingKey {
case recentCount = "RecentCount"
}
}
To decode I am using this line but I am not getting how do I check for "data" is empty of not.
let strResponseData = try JSONDecoder().decode(RecentResult.self, from: data!)
回答1:
General tip for when you have something like an optional in your data...
If you have this ..
struct example: Decodable {
let name: String
let nickname: String
let tag: String
}
those three HAVE TO be there, they can't be "nil", they cannot be nonexistent in the JSON.
So if "nickname" is simply not in the json, it just won't parse.
On the other hand. If you do this, notice the question mark:
struct example: Decodable {
let name: String
let nickname: String?
let tag: String
}
then the .nickname
field can actually be nil
So then, you can say something like
if blah.nickname == nil { print("no nickname in the json!") }
You could say the literal answer to your question "How to check if field XYZ is empty" is "if strResponseData.xyz == nil" ...
But you have to indicate to the parser that in the json it may be either nil (ie, the json looks like this ... "nickname":nil ) or it is just plain missing from the json (there's just no field "nickname" in the json).
The way you do that is with the "?".
来源:https://stackoverflow.com/questions/60905397/how-to-check-response-codable-value-is-empty-or-not