gpt4 book ai didi

json - 快速 json null 检查

转载 作者:行者123 更新时间:2023-11-30 10:03:15 26 4
gpt4 key购买 nike

我对 swift 的了解还很差。 (也是英语!抱歉!)

在解码的 json 字典中检查 null。

这是搜索一些提示后的工作代码。但我认为这段代码非常糟糕。

有什么想法可以制作这段华丽的代码吗?

var v_desc = ""
var v_sword = ""
var v_sortk = 0
for (_, value) in api_result {
if let ch_descr = value["description"] as? String {
v_desc = ch_descr
} else {
v_desc = ""
}
if let ch_sword = value["search_word"] as? String {
v_sword = ch_sword
} else {
v_sword = ""
}
if let ch_sortk = value["sort_key"] as? Int {
v_sortk = ch_sortk
} else {
v_sortk = 0
}

self.cell_data.append(aps_tag(catg_UID: value["ctag_UID"] as! Int, set_code: value["set_code"] as! Int, title: value["title"] as! String, description: v_desc, search_word: v_sword, nums: value["nums"] as! Int, sort_key: v_sortk))

}

最佳答案

华丽是主观的,但您可以使用 nil-coalescing 运算符 (??) 使其更加简洁:

for (_, value) in api_result {
let catg_UID = value["ctag_UID"] as! Int
let set_code = value["set_code"] as! Int
let title = value["title"] as! String
let nums = value["nums"] as! Int

let v_desc = value["description"] as? String ?? ""
let v_sword = value["search_word"] as? String ?? ""
let v_sortk = value["sort_key"] as? Int ?? 0

let aps_tag = aps_tag(catg_UID: catg_UID, set_code: set_code, title: title, description: v_desc, search_word: v_sword, nums: nums, sort_key: v_sortk)
self.cell_data.append(aps_tag)
}

另一件事:那些 snake_case 变量和函数名称让我想起了很多 C/C++。对我来说看起来不太 Swifty,但这是个人喜好。

关于json - 快速 json null 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37336298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com