Created
December 29, 2019 06:38
-
-
Save indyfromoz/26e55d06a872ab3abefacd64891b9c63 to your computer and use it in GitHub Desktop.
JSON decoder that handles an absent value or a null value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improvement