gpt4 book ai didi

ios - 使用 Swift 4 Decodable 将字符串 JSON 响应转换为 bool 值

转载 作者:行者123 更新时间:2023-11-28 09:35:30 24 4
gpt4 key购买 nike

我正在重构一些我以前使用第三方 JSON 解析器的项目,我遇到了一个以字符串形式返回 bool 值的愚蠢网站。

这是来自 JSON 响应的相关片段:

{
"delay": "false",
/* a bunch of other keys*/
}

我的解码结构如下所示:

struct MyJSONStruct: Decodable {
let delay: Bool
// the rest of the keys
}

我如何将 JSON 响应中返回的字符串转换为 Bool 以匹配我在 Swift 4 中的结构?同时this post很有帮助,我不知道如何将字符串响应转换为 bool 值。

最佳答案

基本上您必须编写一个自定义初始化器,但是如果有很多好的键,但只有一个键可以从一种类型映射到另一种类型,那么计算属性可能会有用

struct MyJSONStruct: Decodable {
var delay: String
// the rest of the keys

var boolDelay : Bool {
get { return delay == "true" }
set { delay = newValue ? "true" : "false" }
}
}

关于ios - 使用 Swift 4 Decodable 将字符串 JSON 响应转换为 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46849860/

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