{ init(from decoder: Decoder) throws } public protocol Encodable { func encode(to encoder: Encoder) throws } public protocol CodingKey { public var stringValue: String { get } public init?(stringValue: String) public var intValue: Int? { get } public init?(intValue: Int) }
public let codingPath: [CodingKey] public let debugDescription: String public let underlyingError: Error? } case typeMismatch(Any.Type, Context) case valueNotFound(Any.Type, Context) case keyNotFound(CodingKey, Context) case dataCorrupted(Context) } public enum EncodingError : Error { public struct Context { public let codingPath: [CodingKey] public let debugDescription: String public let underlyingError: Error? } case invalidValue(Any, Context) }
for dictionary coding • Unkeyed ... for array coding • SingleValue ... for single primitive value coding • 3 containers are used as intermediate hierarchical representation for arbitrary (de)serialization (e.g. JSONSerialization with [String: Any]).
(and optionally, Int key) • superDecoder / superEncoder • Used when subclassing • Error Handling (DecodingError / EncodingError) • codingPath records the error path and outputs its detail
TryParsec (try! Swift Tokyo 2016) case string(Swift.String) case number(Double) case bool(Swift.Bool) case null case array([JSON]) case object([Swift.String : JSON]) } ... func toJSON() -> JSON { return .object([ "message": .string(message), "user": .object(["name": .string(user.name), "age": .number(user.age)]) ]) }
• (Hopefully) ends 3 years of Swift JSON library wars • Beautiful protocol-oriented design • Replaces NSCoder and reflection(Mirror)-based coding • More improvements are possible by [SE-0143] Conditional conformances • Swift 5 will be game changing! #$
• (Hopefully) ends 3 years of Swift JSON library wars • Beautiful protocol-oriented design • Replaces NSCoder and reflection(Mirror)-based coding • More improvements are possible by [SE-0143] Conditional conformances • Swift 5 will be game changing! #$