使用Swift 4 Decodable将字符串JSON响应转换为布尔值 [英] Convert string JSON response to a boolean using Swift 4 Decodable

查看:107
本文介绍了使用Swift 4 Decodable将字符串JSON响应转换为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重构以前使用第三方JSON解析器的一些项目,并且遇到了一个愚蠢的网站,该网站返回布尔值作为字符串.

I'm refactoring some projects where I'd previously used third-party JSON parsers and I've encountered a goofy site that returns a boolean as a string.

这是JSON响应中的相关代码段:

This is the relevant snippet from the JSON response:

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

我的解码结构如下:

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

如何将JSON响应中返回的字符串转换为Bool以匹配Swift 4中的结构?虽然这篇文章很有帮助,我不知道如何将字符串响应转换为布尔值.

How would I convert the string returned in the JSON response into a Bool to match my struct in Swift 4? While this post was helpful, I can't figure out how to turn a string response into a boolean value.

推荐答案

基本上,您必须编写一个自定义的初始化程序,但是如果有许多 good 键,但只有一个键可以将一个类型映射到另一个计算属性可能有用

Basically you have to write a custom initializer but if there are many good keys but only one to map from a type to another a computed property might be useful

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

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

这篇关于使用Swift 4 Decodable将字符串JSON响应转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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