Skip to content

Commit f7cd0a6

Browse files
author
Itai Ferber
committed
Add Codable conformance to Array
1 parent 2ce58c1 commit f7cd0a6

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

stdlib/public/core/Codable.swift

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2701,6 +2701,45 @@ public extension RawRepresentable where RawValue == String, Self : Decodable {
27012701
}
27022702
}
27032703

2704+
//===----------------------------------------------------------------------===//
2705+
// Collection Extensions
2706+
//===----------------------------------------------------------------------===//
2707+
2708+
// FIXME: Uncomment when conditional conformance is available.
2709+
extension Array : Codable /* where Element : Codable */ {
2710+
public init(from decoder: Decoder) throws {
2711+
guard Element.self is Decodable.Type else {
2712+
preconditionFailure("Array<\(Element.self)> does not conform to Decodable because \(Element.self) does not conform to Decodable.")
2713+
}
2714+
2715+
self.init()
2716+
2717+
let metaType = (Element.self as! Decodable.Type)
2718+
var container = try decoder.unkeyedContainer()
2719+
while !container.isAtEnd {
2720+
// superDecoder fetches the next element as a container and wraps a Decoder around it.
2721+
// This is normally appropriate for decoding super, but this is really what we want to do.
2722+
let subdecoder = try container.superDecoder()
2723+
let element = try metaType.init(from: subdecoder)
2724+
self.append(element as! Element)
2725+
}
2726+
}
2727+
2728+
public func encode(to encoder: Encoder) throws {
2729+
guard Element.self is Encodable.Type else {
2730+
preconditionFailure("Array<\(Element.self)> does not conform to Encodable because \(Element.self) does not conform to Encodable.")
2731+
}
2732+
2733+
var container = encoder.unkeyedContainer()
2734+
for element in self {
2735+
// superEncoder appends an empty element and wraps an Encoder around it.
2736+
// This is normally appropriate for encoding super, but this is really what we want to do.
2737+
let subencoder = container.superEncoder()
2738+
try (element as! Encodable).encode(to: subencoder)
2739+
}
2740+
}
2741+
}
2742+
27042743
//===----------------------------------------------------------------------===//
27052744
// Convenience Default Implementations
27062745
//===----------------------------------------------------------------------===//

0 commit comments

Comments
 (0)