File tree Expand file tree Collapse file tree 2 files changed +30
-1
lines changed
Expand file tree Collapse file tree 2 files changed +30
-1
lines changed Original file line number Diff line number Diff 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+
118129public extension Encoding {
119130 static var nullValue : Self {
120131 . init { _, encoder in
Original file line number Diff line number Diff 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 }
You can’t perform that action at this time.
0 commit comments