Search code examples
iosjsonswiftswift4decodable

Convert string JSON response to a boolean using Swift 4 Decodable


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.

This is the relevant snippet from the JSON response:

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

My struct for Decoding looks like this:

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

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.


Solution

  • 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" }
       }
    }