Skip to content

Commit 912919a

Browse files
committed
[TSCUtility] Use a separate array property wrapper for PolymorphicCodable
Conditional conformance doesn't seem to work that well.
1 parent 39fb181 commit 912919a

File tree

2 files changed

+9
-14
lines changed

2 files changed

+9
-14
lines changed

Diff for: Sources/TSCUtility/PolymorphicCodable.swift

+7-13
Original file line numberDiff line numberDiff line change
@@ -42,21 +42,15 @@ public struct PolymorphicCodable<T: PolymorphicCodableProtocol>: Codable {
4242
}
4343
}
4444

45-
extension Array: PolymorphicCodableProtocol where Element: PolymorphicCodableProtocol {
46-
public static var implementations: [PolymorphicCodableProtocol.Type] {
47-
return [Array<Element>.self]
48-
}
45+
@propertyWrapper
46+
public struct PolymorphicCodableArray<T: PolymorphicCodableProtocol>: Codable {
47+
public let value: [PolymorphicCodable<T>]
4948

50-
public func encode(to encoder: Encoder) throws {
51-
try self.map{ PolymorphicCodable(wrappedValue: $0) }.encode(to: encoder)
49+
public init(wrappedValue value: [T]) {
50+
self.value = value.map{ PolymorphicCodable(wrappedValue: $0) }
5251
}
5352

54-
public init(from decoder: Decoder) throws {
55-
var container = try decoder.unkeyedContainer()
56-
var items: [PolymorphicCodable<Element>] = []
57-
while !container.isAtEnd {
58-
items.append(try container.decode(PolymorphicCodable<Element>.self))
59-
}
60-
self = items.map{ $0.value }
53+
public var wrappedValue: [T] {
54+
return value.map{ $0.value }
6155
}
6256
}

Diff for: Tests/TSCUtilityTests/PolymorphicCodableTests.swift

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ struct Animals: Codable {
3434
@PolymorphicCodable
3535
var animal2: Animal
3636

37-
@PolymorphicCodable
37+
@PolymorphicCodableArray
3838
var animals: [Animal]
3939
}
4040

@@ -58,6 +58,7 @@ final class PolymorphicCodableTests: XCTestCase {
5858

5959
XCTAssertEqual(decoded.animals.count, 2)
6060
XCTAssertEqual(decoded.animals.map{ $0.age }, [5, 3])
61+
XCTAssertEqual(decoded.animals.map{ String(reflecting: $0) }, ["TSCUtilityTests.Dog", "TSCUtilityTests.Cat"])
6162
}
6263
}
6364

0 commit comments

Comments
 (0)