Skip to content

Instantly share code, notes, and snippets.

@indyfromoz
Created December 29, 2019 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indyfromoz/26e55d06a872ab3abefacd64891b9c63 to your computer and use it in GitHub Desktop.
Save indyfromoz/26e55d06a872ab3abefacd64891b9c63 to your computer and use it in GitHub Desktop.
JSON decoder that handles an absent value or a null value
extension KeyedDecodingContainer {
func decodeIfPresentAndNotNullString<T>(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable {
do {
return try decodeIfPresent(type, forKey: key)
} catch {
if let valueAsString = try decodeIfPresent(String.self, forKey: key), valueAsString == "<null>" {
return nil
} else {
throw error
}
}
}
}
@indyfromoz
Copy link
Author

Improvement

 struct Nullable<T: Decodable>: Decodable {
     let value: T?
 
     init(from decoder: Decoder) throws {
         let container = try decoder.singleValueContainer()
         do {
             value = try container.decode(T.self)
         } catch {
             switch error {
             case DecodingError.valueNotFound:
                 value = nil
             case DecodingError.typeMismatch where try container.decode(String.self) == "<null>":
                 value = nil
             default:
                 throw error
             }
         }
     }
 }
 
 struct Test: Decodable {
     let nullArray: Nullable<Array<Int>>
     let nullStringArray: Nullable<Array<Int>>
     let array: Nullable<Array<Int>>
 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment