如何检查响应编码值是否为空? [英] How to check response codable value is empty or not?

查看:30
本文介绍了如何检查响应编码值是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也是 swift 和 codable 的新手.我有以下编码.我在RecentResult"中收到 API 的所有响应.我想检查数据"是否为空.如何检查?

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!)

推荐答案

当您的数据中有类似可选项时的一般提示...

General tip for when you have something like an optional in your data...

如果你有这个..

struct example: Decodable {
  let name: String
  let nickname: String
  let tag: String
}

这三个必须在那里,它们不能是nil",它们不能在 JSON 中不存在.

those three HAVE TO be there, they can't be "nil", they cannot be nonexistent in the JSON.

所以如果昵称"根本不在 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
}

那么 .nickname 字段实际上可以是 nil

then the .nickname field can actually be nil

那么,你可以这样说

if blah.nickname == nil { print("no nickname in the json!") }


您可以说出问题如何检查 XYZ 字段是否为空"的字面答案;是如果 strResponseData.xyz == nil";...


You could say the literal answer to your question "How to check if field XYZ is empty" is "if strResponseData.xyz == nil" ...

但是您必须向解析器指出,在 json 中它可能是 nil(即 json 看起来像这样......昵称":nil)或者它只是从 json 中丢失(只有json 中没有字段昵称").

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 "?".

这篇关于如何检查响应编码值是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆