Skip to content

Commit 9d9de32

Browse files
committed
Add sequence encoding support.
1 parent 35aa3ca commit 9d9de32

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

Sources/Coding/Encoding.swift

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ public extension Encoding where Value: Encodable {
101101
}
102102

103103
static var unkeyed: Self {
104-
Self { value, encoder in
104+
.init { value, encoder in
105105
var container = encoder.unkeyedContainer()
106106
try container.encode(value)
107107
}
@@ -115,6 +115,17 @@ public extension Encoding where Value: Encodable {
115115
}
116116
}
117117

118+
public extension Encoding where Value: Sequence, Value.Element: Encodable {
119+
static func arrayOf(_ encoding: Encoding<Value.Element>) -> Self {
120+
.init { value, encoder in
121+
var container = encoder.unkeyedContainer()
122+
for element in value {
123+
try encoding.encode(element, container.superEncoder())
124+
}
125+
}
126+
}
127+
}
128+
118129
public extension Encoding {
119130
static var nullValue: Self {
120131
.init { _, encoder in

Tests/CodingTests/EncodingTests.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,24 @@ final class EncodingTests: XCTestCase {
363363
)
364364
}
365365

366+
// MARK: - Collection Encoding
367+
368+
func testEncodeArrayWithCustomEncodingForEachValue() {
369+
let strings = ["One", "Two", "Three"]
370+
371+
XCTAssertEqual(
372+
"[\"One\",\"Two\",\"Three\"]",
373+
stringValue(try encoder.encode(strings, as: .singleValue))
374+
)
375+
376+
let uppercased: Encoding<String> = .singleValue.pullback { $0.uppercased() }
377+
378+
XCTAssertEqual(
379+
"[\"ONE\",\"TWO\",\"THREE\"]",
380+
stringValue(try encoder.encode(strings, as: .arrayOf(uppercased)))
381+
)
382+
}
383+
366384
private func stringValue(_ data: Data) -> String {
367385
String(data: data, encoding: .utf8)!
368386
}

0 commit comments

Comments
 (0)