From 49e39f697465d42a85c5557d8ca3f3ae0649d6a8 Mon Sep 17 00:00:00 2001 From: Rob Napier Date: Sun, 17 Jul 2022 11:28:27 -0400 Subject: [PATCH] Add failedDecodes to LossyArray --- Sources/BetterCodable/LossyArray.swift | 23 +++++++++++++++++-- .../BetterCodableTests/LossyArrayTests.swift | 4 ++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Sources/BetterCodable/LossyArray.swift b/Sources/BetterCodable/LossyArray.swift index 6813124..75fe071 100644 --- a/Sources/BetterCodable/LossyArray.swift +++ b/Sources/BetterCodable/LossyArray.swift @@ -6,10 +6,18 @@ @propertyWrapper public struct LossyArray { public var wrappedValue: [T] + public var projectedValue: Self { self } public init(wrappedValue: [T]) { self.wrappedValue = wrappedValue } + + public struct FailedDecode { + var codingPath: [CodingKey] + var error: Error + } + + public var failedDecodes: [FailedDecode] = [] } extension LossyArray: Decodable where T: Decodable { @@ -19,16 +27,19 @@ extension LossyArray: Decodable where T: Decodable { var container = try decoder.unkeyedContainer() var elements: [T] = [] + var failedDecodes: [FailedDecode] = [] while !container.isAtEnd { do { let value = try container.decode(T.self) elements.append(value) } catch { + failedDecodes.append(FailedDecode(codingPath: container.codingPath, error: error)) _ = try? container.decode(AnyDecodableValue.self) } } self.wrappedValue = elements + self.failedDecodes = failedDecodes } } @@ -38,5 +49,13 @@ extension LossyArray: Encodable where T: Encodable { } } -extension LossyArray: Equatable where T: Equatable { } -extension LossyArray: Hashable where T: Hashable { } +extension LossyArray: Equatable where T: Equatable { + public static func == (lhs: LossyArray, rhs: LossyArray) -> Bool { + lhs.wrappedValue == rhs.wrappedValue + } +} +extension LossyArray: Hashable where T: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(wrappedValue) + } +} diff --git a/Tests/BetterCodableTests/LossyArrayTests.swift b/Tests/BetterCodableTests/LossyArrayTests.swift index f075388..e9427fd 100644 --- a/Tests/BetterCodableTests/LossyArrayTests.swift +++ b/Tests/BetterCodableTests/LossyArrayTests.swift @@ -17,6 +17,8 @@ class LossyArrayTests: XCTestCase { let fixture = try JSONDecoder().decode(Fixture.self, from: jsonData) XCTAssertEqual(fixture.values, [1, 3, 4]) XCTAssertEqual(fixture.nonPrimitiveValues, []) + XCTAssertEqual(fixture.$values.failedDecodes.count, 1) + XCTAssertEqual(fixture.$nonPrimitiveValues.failedDecodes.count, 1) } func testDecodingLossyArrayIgnoresLossyElements() throws { @@ -24,6 +26,8 @@ class LossyArrayTests: XCTestCase { let fixture = try JSONDecoder().decode(Fixture.self, from: jsonData) XCTAssertEqual(fixture.values, [1, 4]) XCTAssertEqual(fixture.nonPrimitiveValues, []) + XCTAssertEqual(fixture.$values.failedDecodes.count, 3) + XCTAssertEqual(fixture.$nonPrimitiveValues.failedDecodes.count, 1) } func testEncodingDecodedLossyArrayIgnoresFailableElements() throws {