Last active
January 11, 2023 08:25
-
-
Save gonzalezreal/52b1394f6039dff3802c4ebe0de16302 to your computer and use it in GitHub Desktop.
A technique to avoid having optional array properties in your models when decoding JSON using Swift 4
This file contains hidden or 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
/// A type that has an "empty" representation. | |
public protocol EmptyRepresentable { | |
static func empty() -> Self | |
} | |
extension Array: EmptyRepresentable { | |
public static func empty() -> Array<Element> { | |
return Array() | |
} | |
} | |
extension KeyedDecodingContainer { | |
public func decode<T>(_ type: T.Type, forKey key: KeyedDecodingContainer<K>.Key) throws -> T where T: Decodable & EmptyRepresentable { | |
if let result = try decodeIfPresent(T.self, forKey: key) { | |
return result | |
} else { | |
return T.empty() | |
} | |
} | |
} | |
struct Model: Decodable { | |
let id: Int | |
// Instead of making this property optional because it may be not present | |
// in the JSON, we leverage the `KeyedDecodingContainer` extension above | |
// to have an empty array in that case. | |
let items: [String] | |
} | |
let json = """ | |
{ | |
"id": 42 | |
} | |
""".data(using: .utf8)! | |
let decoder = JSONDecoder() | |
do { | |
let model = try decoder.decode(Model.self, from: json) | |
print(model) | |
} catch { | |
print(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment