Created
June 14, 2024 17:25
-
-
Save IanKeen/9debb90afcbe0aecabaa39b0aa18d201 to your computer and use it in GitHub Desktop.
PropertyWrapper: Allows for single elements in an array to "fail" decoding without failing the entire operation
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
@propertyWrapper | |
public struct AllowDecodingFailures<T: Codable>: Codable { | |
public var wrappedValue: [T] | |
public var errors: [Error] | |
public var projectedValue: AllowDecodingFailures<T> { self } | |
private struct Empty: Decodable { } | |
public init(wrappedValue: [T]) { | |
self.init(wrappedValue: wrappedValue, errors: []) | |
} | |
private init(wrappedValue: [T], errors: [Error]) { | |
self.wrappedValue = wrappedValue | |
self.errors = errors | |
} | |
public init(from decoder: Decoder) throws { | |
var container = try decoder.unkeyedContainer() | |
var values: [T] = [] | |
var errors: [Error] = [] | |
while !container.isAtEnd { | |
do { | |
try values.append(container.decode(T.self)) | |
} catch let error { | |
errors.append(error) | |
_ = try? container.decode(Empty.self) | |
} | |
} | |
self.init(wrappedValue: values, errors: errors) | |
} | |
public func encode(to encoder: Encoder) throws { | |
try wrappedValue.encode(to: encoder) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment