Adr*_*ian 0 json ios swift swift4 decodable
我正在重构一些我之前使用过第三方JSON解析器的项目,而且我遇到了一个愚蠢的网站,它将一个布尔值作为字符串返回.
这是JSON响应的相关片段:
{
"delay": "false",
/* a bunch of other keys*/
}
Run Code Online (Sandbox Code Playgroud)
我的Decoding结构如下所示:
struct MyJSONStruct: Decodable {
let delay: Bool
// the rest of the keys
}
Run Code Online (Sandbox Code Playgroud)
我如何将JSON响应中返回的字符串转换为Bool以匹配Swift 4中的结构?虽然这篇文章很有帮助,但我无法弄清楚如何将字符串响应转换为布尔值.
基本上你必须编写一个自定义初始化程序但是如果有很多好的键但只有一个从一个类型映射到另一个类型,则计算属性可能是有用的
struct MyJSONStruct: Decodable {
var delay: String
// the rest of the keys
var boolDelay : Bool {
get { return delay == "true" }
set { delay = newValue ? "true" : "false" }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1801 次 |
| 最近记录: |