Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gonzalezreal/52b1394f6039dff3802c4ebe0de16302 to your computer and use it in GitHub Desktop.
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
/// 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