From 1c9a21e318950198f14d727e44980458f243c954 Mon Sep 17 00:00:00 2001 From: iwill Date: Thu, 1 Jul 2021 11:30:58 +0800 Subject: [PATCH 01/20] sty: comments --- Sources/ExCodable/ExCodable+DEPRECATED.swift | 35 +++++++++++ Sources/ExCodable/ExCodable.swift | 61 +++++++------------- 2 files changed, 56 insertions(+), 40 deletions(-) create mode 100644 Sources/ExCodable/ExCodable+DEPRECATED.swift diff --git a/Sources/ExCodable/ExCodable+DEPRECATED.swift b/Sources/ExCodable/ExCodable+DEPRECATED.swift new file mode 100644 index 0000000..6666bb6 --- /dev/null +++ b/Sources/ExCodable/ExCodable+DEPRECATED.swift @@ -0,0 +1,35 @@ +// +// ExCodable.swift +// ExCodable +// +// Created by Mr. Ming on 2021-07-01. +// Copyright (c) 2021 Mr. Ming . Released under the MIT license. +// + +import Foundation + +public extension ExCodable { + @available(*, deprecated, renamed: "encode(to:with:nonnull:throws:)") + func encode(with keyMapping: [KeyMap], using encoder: Encoder) { + try? encode(to: encoder, with: keyMapping) + } + @available(*, deprecated, renamed: "decode(from:with:nonnull:throws:)") + mutating func decode(with keyMapping: [KeyMap], using decoder: Decoder) { + try? decode(from: decoder, with: keyMapping) + } + @available(*, deprecated, renamed: "decodeReference(from:with:nonnull:throws:)") + func decodeReference(with keyMapping: [KeyMap], using decoder: Decoder) { + try? decodeReference(from: decoder, with: keyMapping) + } +} + +@available(*, deprecated, renamed: "append(decodingTypeConverter:)") +public protocol KeyedDecodingContainerCustomTypeConversion: ExCodableDecodingTypeConverter { + func decodeForTypeConversion(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? +} +@available(*, deprecated) +public extension KeyedDecodingContainerCustomTypeConversion { + func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) throws -> T? { + return decodeForTypeConversion(container, codingKey: codingKey, as: type) + } +} diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 8ef6c24..e5f69ad 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -24,7 +24,18 @@ public protocol ExCodable: Codable { static var keyMapping: [KeyMap] { get } } +// default implementation for Encodable +public extension ExCodable where Root == Self { + func encode(to encoder: Encoder) throws { + try encode(to: encoder, with: Self.keyMapping) + } +} + +// MARK: - keyMapping + +// encode/decode public extension ExCodable { + static var keyMapping: [KeyMap] { [] } // default implementation for optional property func encode(to encoder: Encoder, with keyMapping: [KeyMap], nonnull: Bool = false, throws: Bool = false) throws { try keyMapping.forEach { try $0.encode(self, encoder, nonnull, `throws`) } } @@ -35,13 +46,6 @@ public extension ExCodable { try keyMapping.forEach { try $0.decodeReference?(self, decoder, nonnull, `throws`) } } } -public extension ExCodable where Root == Self { - func encode(to encoder: Encoder) throws { - try encode(to: encoder, with: Self.keyMapping) - } -} - -// MARK: - public final class KeyMap { fileprivate let encode: (_ root: Root, _ encoder: Encoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void @@ -119,7 +123,7 @@ public extension Decoder { // , abortIfNull nonnull: Bool = false, abortOnError } } -// MARK: - +// MARK: - Encoder&Decoder public extension Encoder { @@ -225,13 +229,18 @@ public extension Decoder { } } -private struct ExCodingKey: CodingKey { - let stringValue: String, intValue: Int? +// MARK: - ExCodingKey + +private struct ExCodingKey { + public let stringValue: String, intValue: Int? init(_ stringValue: String) { (self.stringValue, self.intValue) = (stringValue, nil) } init(_ stringValue: Substring) { self.init(String(stringValue)) } - init?(stringValue: String) { self.init(stringValue) } init(_ intValue: Int) { (self.intValue, self.stringValue) = (intValue, String(intValue)) } - init?(intValue: Int) { self.init(intValue) } +} + +extension ExCodingKey: CodingKey { + public init?(stringValue: String) { self.init(stringValue) } + public init?(intValue: Int) { self.init(intValue) } } // MARK: - alternative-keys + nested-keys + type-conversion @@ -498,31 +507,3 @@ extension JSONDecoder: DataDecoder {} extension PropertyListEncoder: DataEncoder {} extension PropertyListDecoder: DataDecoder {} #endif - -// MARK: - #### DEPRECATED #### - -public extension ExCodable { - @available(*, deprecated, renamed: "encode(to:with:nonnull:throws:)") - func encode(with keyMapping: [KeyMap], using encoder: Encoder) { - try? encode(to: encoder, with: keyMapping) - } - @available(*, deprecated, renamed: "decode(from:with:nonnull:throws:)") - mutating func decode(with keyMapping: [KeyMap], using decoder: Decoder) { - try? decode(from: decoder, with: keyMapping) - } - @available(*, deprecated, renamed: "decodeReference(from:with:nonnull:throws:)") - func decodeReference(with keyMapping: [KeyMap], using decoder: Decoder) { - try? decodeReference(from: decoder, with: keyMapping) - } -} - -@available(*, deprecated, renamed: "append(decodingTypeConverter:)") -public protocol KeyedDecodingContainerCustomTypeConversion: ExCodableDecodingTypeConverter { - func decodeForTypeConversion(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? -} -@available(*, deprecated) -public extension KeyedDecodingContainerCustomTypeConversion { - func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) throws -> T? { - return decodeForTypeConversion(container, codingKey: codingKey, as: type) - } -} From b46d80f41e509bf08dccb19cf67bc6cc0b7c2144 Mon Sep 17 00:00:00 2001 From: iwill Date: Fri, 2 Jul 2021 00:01:15 +0800 Subject: [PATCH 02/20] !!!: 1.x, keyMapping -> propertyWrapper --- ExCodable.podspec | 2 +- Sources/ExCodable/ExCodable+DEPRECATED.swift | 95 ++++++++++- Sources/ExCodable/ExCodable.swift | 167 ++++++++++--------- Tests/ExCodableTests/ExCodableTests.swift | 165 +++++------------- 4 files changed, 228 insertions(+), 201 deletions(-) diff --git a/ExCodable.podspec b/ExCodable.podspec index b595796..fa839ab 100644 --- a/ExCodable.podspec +++ b/ExCodable.podspec @@ -3,7 +3,7 @@ Pod::Spec.new do |s| # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # s.name = "ExCodable" # export LIB_VERSION=$(git describe --tags `git rev-list --tags --max-count=1`) - s.version = ENV["LIB_VERSION"] || "0.6.0" + s.version = ENV["LIB_VERSION"] || "1.0.0-alpha" s.summary = "Key-Mapping Extensions for Swift Codable" # s.description = "Key-Mapping Extensions for Swift Codable." s.homepage = "https://github.com/iwill/ExCodable" diff --git a/Sources/ExCodable/ExCodable+DEPRECATED.swift b/Sources/ExCodable/ExCodable+DEPRECATED.swift index 6666bb6..7046def 100644 --- a/Sources/ExCodable/ExCodable+DEPRECATED.swift +++ b/Sources/ExCodable/ExCodable+DEPRECATED.swift @@ -8,7 +8,100 @@ import Foundation -public extension ExCodable { +// MARK: - keyMapping + +@available(*, deprecated, message: "use `@ExCodable` property wrapper instead") +public protocol ExCodableProtocol: Codable { + associatedtype Root = Self where Root: ExCodableProtocol + static var keyMapping: [KeyMap] { get } +} + +@available(*, deprecated) +public extension ExCodableProtocol where Root == Self { + + // default implementation of ExCodableProtocol + static var keyMapping: [KeyMap] { [] } + + // default implementation of Encodable + func encode(to encoder: Encoder) throws { + try encode(to: encoder, with: Self.keyMapping) + try encode(to: encoder, nonnull: false, throws: false) + } + + func decode(from decoder: Decoder) throws { + try decode(from: decoder, nonnull: false, throws: false) + } +} + +@available(*, deprecated) +public extension ExCodableProtocol { + func encode(to encoder: Encoder, with keyMapping: [KeyMap], nonnull: Bool = false, throws: Bool = false) throws { + try keyMapping.forEach { try $0.encode(self, encoder, nonnull, `throws`) } + } + mutating func decode(from decoder: Decoder, with keyMapping: [KeyMap], nonnull: Bool = false, throws: Bool = false) throws { + try keyMapping.forEach { try $0.decode?(&self, decoder, nonnull, `throws`) } + } + func decodeReference(from decoder: Decoder, with keyMapping: [KeyMap], nonnull: Bool = false, throws: Bool = false) throws { + try keyMapping.forEach { try $0.decodeReference?(self, decoder, nonnull, `throws`) } + } +} + +@available(*, deprecated, message: "use `@ExCodable` property wrapper instead") +public final class KeyMap { + fileprivate let encode: (_ root: Root, _ encoder: Encoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void + fileprivate let decode: ((_ root: inout Root, _ decoder: Decoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void)? + fileprivate let decodeReference: ((_ root: Root, _ decoder: Decoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void)? + private init(encode: @escaping (_ root: Root, _ encoder: Encoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void, + decode: ((_ root: inout Root, _ decoder: Decoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void)?, + decodeReference: ((_ root: Root, _ decoder: Decoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void)?) { + (self.encode, self.decode, self.decodeReference) = (encode, decode, decodeReference) + } +} + +@available(*, deprecated) +public extension KeyMap { + convenience init(_ keyPath: WritableKeyPath, to codingKeys: String ..., nonnull: Bool? = nil, throws: Bool? = nil) { + self.init(encode: { root, encoder, nonnullAll, throwsAll in + try encoder.encode(root[keyPath: keyPath], for: codingKeys.first!, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) + }, decode: { root, decoder, nonnullAll, throwsAll in + if let value: Value = try decoder.decode(codingKeys, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) { + root[keyPath: keyPath] = value + } + }, decodeReference: nil) + } + convenience init(_ keyPath: WritableKeyPath, to codingKeys: Key ..., nonnull: Bool? = nil, throws: Bool? = nil) { + self.init(encode: { root, encoder, nonnullAll, throwsAll in + try encoder.encode(root[keyPath: keyPath], for: codingKeys.first!, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) + }, decode: { root, decoder, nonnullAll, throwsAll in + if let value: Value = try decoder.decode(codingKeys, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) { + root[keyPath: keyPath] = value + } + }, decodeReference: nil) + } + convenience init(ref keyPath: ReferenceWritableKeyPath, to codingKeys: String ..., nonnull: Bool? = nil, throws: Bool? = nil) { + self.init(encode: { root, encoder, nonnullAll, throwsAll in + try encoder.encode(root[keyPath: keyPath], for: codingKeys.first!, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) + }, decode: nil, decodeReference: { root, decoder, nonnullAll, throwsAll in + if let value: Value = try decoder.decode(codingKeys, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) { + root[keyPath: keyPath] = value + } + }) + } + convenience init(ref keyPath: ReferenceWritableKeyPath, to codingKeys: Key ..., nonnull: Bool? = nil, throws: Bool? = nil) { + self.init(encode: { root, encoder, nonnullAll, throwsAll in + try encoder.encode(root[keyPath: keyPath], for: codingKeys.first!, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) + }, decode: nil, decodeReference: { root, decoder, nonnullAll, throwsAll in + if let value: Value = try decoder.decode(codingKeys, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) { + root[keyPath: keyPath] = value + } + }) + } +} + +// MARK: - + +@available(*, deprecated) +public extension ExCodableProtocol { @available(*, deprecated, renamed: "encode(to:with:nonnull:throws:)") func encode(with keyMapping: [KeyMap], using encoder: Encoder) { try? encode(to: encoder, with: keyMapping) diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index e5f69ad..4b14cd2 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -18,86 +18,104 @@ import Foundation * * - seealso: [Usage](https://github.com/iwill/ExCodable#usage) from GitGub * - seealso: `ExCodableTests.swift` form the source code + * - seealso: Idea from [Decoding and overriding](https://www.swiftbysundell.com/articles/property-wrappers-in-swift/#decoding-and-overriding), by John Sundell. */ -public protocol ExCodable: Codable { - associatedtype Root = Self where Root: ExCodable - static var keyMapping: [KeyMap] { get } -} -// default implementation for Encodable -public extension ExCodable where Root == Self { - func encode(to encoder: Encoder) throws { - try encode(to: encoder, with: Self.keyMapping) +@propertyWrapper +public final class ExCodable { + fileprivate let stringKeys: [String]? + fileprivate let nonnull, `throws`: Bool? + fileprivate let encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)?, decode: ((_ decoder: Decoder) throws -> Value?)? + public var wrappedValue: Value + private init(wrappedValue: Value, stringKeys: [String]? = nil, nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)?, decode: ((_ decoder: Decoder) throws -> Value?)?) { + (self.wrappedValue, self.stringKeys, self.nonnull, self.throws, self.encode, self.decode) = (wrappedValue, stringKeys, nonnull, `throws`, encode, decode) + } + public convenience init(wrappedValue: Value, _ stringKey: String? = nil, nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) { + self.init(wrappedValue: wrappedValue, stringKeys: stringKey.map { [$0] }, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) + } + public convenience init(wrappedValue: Value, _ stringKeys: String..., nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) { + self.init(wrappedValue: wrappedValue, stringKeys: stringKeys, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) + } + public convenience init(wrappedValue: Value, _ codingKeys: CodingKey..., nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) { + self.init(wrappedValue: wrappedValue, stringKeys: codingKeys.map { $0.stringValue }, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) + } +} +extension ExCodable: Equatable where Value: Equatable { + public static func == (lhs: ExCodable, rhs: ExCodable) -> Bool { + return lhs.wrappedValue == rhs.wrappedValue } } -// MARK: - keyMapping +fileprivate protocol EncodablePropertyWrapper { + func encode(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws +} +extension ExCodable: EncodablePropertyWrapper where Value: Encodable { + fileprivate func encode(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws { + if encode != nil { try encode!(encoder, wrappedValue) } + else { try encoder.encode(wrappedValue, for: stringKeys?.first ?? String(label), nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`) } + + } +} -// encode/decode -public extension ExCodable { - static var keyMapping: [KeyMap] { [] } // default implementation for optional property - func encode(to encoder: Encoder, with keyMapping: [KeyMap], nonnull: Bool = false, throws: Bool = false) throws { - try keyMapping.forEach { try $0.encode(self, encoder, nonnull, `throws`) } +fileprivate protocol DecodablePropertyWrapper { + func decode(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool) throws +} +extension ExCodable: DecodablePropertyWrapper where Value: Decodable { + fileprivate func decode(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool) throws { + if let value = decode != nil + ? try decode!(decoder) + : try decoder.decode(stringKeys ?? [String(label)], nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`) { + wrappedValue = value + } } - mutating func decode(from decoder: Decoder, with keyMapping: [KeyMap], nonnull: Bool = false, throws: Bool = false) throws { - try keyMapping.forEach { try $0.decode?(&self, decoder, nonnull, `throws`) } +} + +// MARK: Codable + +public extension Encodable { + func encode(to encoder: Encoder, nonnull: Bool, throws: Bool) throws { + var mirror: Mirror! = Mirror(reflecting: self) + while mirror != nil { + for child in mirror.children where child.label != nil { + try (child.value as? EncodablePropertyWrapper)?.encode(to: encoder, label: child.label!.dropFirst(), nonnull: false, throws: false) + } + mirror = mirror.superclassMirror + } } - func decodeReference(from decoder: Decoder, with keyMapping: [KeyMap], nonnull: Bool = false, throws: Bool = false) throws { - try keyMapping.forEach { try $0.decodeReference?(self, decoder, nonnull, `throws`) } +} + +public extension Decodable { + func decode(from decoder: Decoder, nonnull: Bool, throws: Bool) throws { + var mirror: Mirror! = Mirror(reflecting: self) + while mirror != nil { + for child in mirror.children where child.label != nil { + try (child.value as? DecodablePropertyWrapper)?.decode(from: decoder, label: child.label!.dropFirst(), nonnull: false, throws: false) + } + mirror = mirror.superclassMirror + } } } -public final class KeyMap { - fileprivate let encode: (_ root: Root, _ encoder: Encoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void - fileprivate let decode: ((_ root: inout Root, _ decoder: Decoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void)? - fileprivate let decodeReference: ((_ root: Root, _ decoder: Decoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void)? - private init(encode: @escaping (_ root: Root, _ encoder: Encoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void, - decode: ((_ root: inout Root, _ decoder: Decoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void)?, - decodeReference: ((_ root: Root, _ decoder: Decoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void)?) { - (self.encode, self.decode, self.decodeReference) = (encode, decode, decodeReference) +// MARK: auto implementation for Encodable and Decodable + +public protocol ExAutoEncodable: Encodable {} +public extension ExAutoEncodable { + func encode(to encoder: Encoder) throws { + try encode(to: encoder, nonnull: false, throws: false) } } -public extension KeyMap { - convenience init(_ keyPath: WritableKeyPath, to codingKeys: String ..., nonnull: Bool? = nil, throws: Bool? = nil) { - self.init(encode: { root, encoder, nonnullAll, throwsAll in - try encoder.encode(root[keyPath: keyPath], for: codingKeys.first!, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) - }, decode: { root, decoder, nonnullAll, throwsAll in - if let value: Value = try decoder.decode(codingKeys, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) { - root[keyPath: keyPath] = value - } - }, decodeReference: nil) - } - convenience init(_ keyPath: WritableKeyPath, to codingKeys: Key ..., nonnull: Bool? = nil, throws: Bool? = nil) { - self.init(encode: { root, encoder, nonnullAll, throwsAll in - try encoder.encode(root[keyPath: keyPath], for: codingKeys.first!, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) - }, decode: { root, decoder, nonnullAll, throwsAll in - if let value: Value = try decoder.decode(codingKeys, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) { - root[keyPath: keyPath] = value - } - }, decodeReference: nil) - } - convenience init(ref keyPath: ReferenceWritableKeyPath, to codingKeys: String ..., nonnull: Bool? = nil, throws: Bool? = nil) { - self.init(encode: { root, encoder, nonnullAll, throwsAll in - try encoder.encode(root[keyPath: keyPath], for: codingKeys.first!, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) - }, decode: nil, decodeReference: { root, decoder, nonnullAll, throwsAll in - if let value: Value = try decoder.decode(codingKeys, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) { - root[keyPath: keyPath] = value - } - }) - } - convenience init(ref keyPath: ReferenceWritableKeyPath, to codingKeys: Key ..., nonnull: Bool? = nil, throws: Bool? = nil) { - self.init(encode: { root, encoder, nonnullAll, throwsAll in - try encoder.encode(root[keyPath: keyPath], for: codingKeys.first!, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) - }, decode: nil, decodeReference: { root, decoder, nonnullAll, throwsAll in - if let value: Value = try decoder.decode(codingKeys, nonnull: nonnull ?? nonnullAll, throws: `throws` ?? throwsAll) { - root[keyPath: keyPath] = value - } - }) +public protocol ExAutoDecodable: Decodable { init() } +public extension ExAutoDecodable { + init(from decoder: Decoder) throws { + self.init() + try decode(from: decoder, nonnull: false, throws: false) } } -// MARK: - subscript +public protocol ExAutoCodable: ExAutoEncodable, ExAutoDecodable {} + +// MARK: - Encoder&Decoder public extension Encoder { // , abortIfNull nonnull: Bool = false, abortOnError throws: Bool = false subscript(stringKey: String) -> T? { get { return nil } @@ -123,8 +141,6 @@ public extension Decoder { // , abortIfNull nonnull: Bool = false, abortOnError } } -// MARK: - Encoder&Decoder - public extension Encoder { func encodeNonnullThrows(_ value: T, for stringKey: String) throws { @@ -136,7 +152,7 @@ public extension Encoder { func encode(_ value: T?, for stringKey: String) { try? encode(value, for: stringKey, nonnull: false, throws: false) } - fileprivate func encode(_ value: T?, for stringKey: String, nonnull: Bool = false, throws: Bool = false) throws { + internal/* fileprivate */ func encode(_ value: T?, for stringKey: String, nonnull: Bool = false, throws: Bool = false) throws { let dot: Character = "." guard stringKey.contains(dot), stringKey.count > 1 else { @@ -167,7 +183,7 @@ public extension Encoder { func encode(_ value: T?, for codingKey: K) { try? encode(value, for: codingKey, nonnull: false, throws: false) } - fileprivate func encode(_ value: T?, for codingKey: K, nonnull: Bool = false, throws: Bool = false) throws { + internal/* fileprivate */ func encode(_ value: T?, for codingKey: K, nonnull: Bool = false, throws: Bool = false) throws { var container = self.container(keyedBy: K.self) do { if nonnull { try container.encode(value, forKey: codingKey) } @@ -197,7 +213,7 @@ public extension Decoder { func decode(_ stringKeys: [String], as type: T.Type = T.self) -> T? { return try? decode(stringKeys, as: type, nonnull: false, throws: false) } - fileprivate func decode(_ stringKeys: [String], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false) throws -> T? { + internal/* fileprivate */ func decode(_ stringKeys: [String], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false) throws -> T? { return try decode(stringKeys.map { ExCodingKey($0) }, as: type, nonnull: nonnull, throws: `throws`) } @@ -219,7 +235,7 @@ public extension Decoder { func decode(_ codingKeys: [K], as type: T.Type = T.self) -> T? { return try? decode(codingKeys, as: type, nonnull: false, throws: false) } - fileprivate func decode(_ codingKeys: [K], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false) throws -> T? { + internal/* fileprivate */ func decode(_ codingKeys: [K], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false) throws -> T? { do { let container = try self.container(keyedBy: K.self) return try container.decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`) @@ -233,9 +249,7 @@ public extension Decoder { private struct ExCodingKey { public let stringValue: String, intValue: Int? - init(_ stringValue: String) { (self.stringValue, self.intValue) = (stringValue, nil) } - init(_ stringValue: Substring) { self.init(String(stringValue)) } - init(_ intValue: Int) { (self.intValue, self.stringValue) = (intValue, String(intValue)) } + init(_ stringValue: S) { (self.stringValue, self.intValue) = (stringValue as? String ?? String(stringValue), nil) } } extension ExCodingKey: CodingKey { @@ -245,7 +259,7 @@ extension ExCodingKey: CodingKey { // MARK: - alternative-keys + nested-keys + type-conversion -private extension KeyedDecodingContainer { +fileprivate extension KeyedDecodingContainer { func decodeForAlternativeKeys(_ codingKeys: [Self.Key], as type: T.Type = T.self, nonnull: Bool, throws: Bool) throws -> T? { @@ -422,13 +436,12 @@ public protocol ExCodableDecodingTypeConverter { func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) throws -> T? } -private var _decodingTypeConverters: [ExCodableDecodingTypeConverter] = [] +fileprivate var _decodingTypeConverters: [ExCodableDecodingTypeConverter] = [] public func register(_ decodingTypeConverter: ExCodableDecodingTypeConverter) { _decodingTypeConverters.append(decodingTypeConverter) } // MARK: - Encodable/Decodable -// - seealso: [Codextended](https://github.com/JohnSundell/Codextended) // Encodable.encode() -> Data? public extension Encodable { @@ -503,7 +516,7 @@ public protocol DataDecoder { extension JSONEncoder: DataEncoder {} extension JSONDecoder: DataDecoder {} -#if canImport(ObjectiveC) || swift(>=5.1) +@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension PropertyListEncoder: DataEncoder {} +@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension PropertyListDecoder: DataDecoder {} -#endif diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index 333f83f..6f8d2f4 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -59,93 +59,52 @@ extension TestManualCodable: Codable { // MARK: struct struct TestStruct: Equatable { + @ExCodable("int") private(set) var int: Int = 0 - private(set) var string: String? + @ExCodable("string") + private(set) var string: String? = nil var bool: Bool! } - -extension TestStruct: ExCodable { - - static let keyMapping: [KeyMap] = [ - KeyMap(\.int, to: "int"), - KeyMap(\.string, to: "string"), - ] - - init(from decoder: Decoder) throws { - try decode(from: decoder, with: Self.keyMapping) - } - // `encode` with default implementation can be omitted - // func encode(to encoder: Encoder) throws { - // try encode(to: encoder, with: Self.keyMapping) - // } -} +extension TestStruct: ExAutoCodable {} // MARK: alternative-keys & alternative-keyMapping struct TestAlternativeKeys: Equatable { + @ExCodable("int", "i") var int: Int = 0 - var string: String! -} - -extension TestAlternativeKeys: ExCodable { - - static let keyMapping: [KeyMap] = [ - KeyMap(\.int, to: "int", "i"), - KeyMap(\.string, to: "string", "str", "s") - ] - - static let keyMappingFromLocal: [KeyMap] = [ - KeyMap(\.int, to: "INT"), - KeyMap(\.string, to: "STRING") - ] - - enum LocalKeys: String, CodingKey { - case isLocal = "_IS_LOCAL_" - } - - init(from decoder: Decoder) throws { - let isLocal = decoder[LocalKeys.isLocal] ?? false - try decode(from: decoder, with: isLocal ? Self.keyMappingFromLocal : Self.keyMapping) - } - func encode(to encoder: Encoder) throws { - try encode(to: encoder, with: Self.keyMappingFromLocal) - encoder[LocalKeys.isLocal] = true - } + @ExCodable("string", "str", "s") + var string: String! = nil } +extension TestAlternativeKeys: ExAutoCodable {} // MARK: nested-keys struct TestNestedKeys: Equatable { + @ExCodable var int: Int = 0 - var string: String! -} - -extension TestNestedKeys: ExCodable { - - static let keyMapping: [KeyMap] = [ - KeyMap(\.int, to: "int"), - KeyMap(\.string, to: "nested.string") - ] - - init(from decoder: Decoder) throws { - try decode(from: decoder, with: Self.keyMapping) - } - // func encode(to encoder: Encoder) throws { - // try encode(to: encoder, with: Self.keyMapping) - // } + @ExCodable("nested.string") + var string: String! = nil } +extension TestNestedKeys: ExAutoCodable {} // MARK: custom encode/decode struct TestCustomEncodeDecode: Equatable { + @ExCodable(Keys.int) var int: Int = 0 var string: String? + @ExCodable(encode: { encoder, value in + encoder[Keys.bool] = value + }, decode: { decoder in + return decoder[Keys.bool] + }) + var bool: Bool = false } -extension TestCustomEncodeDecode: ExCodable { +extension TestCustomEncodeDecode: Codable { private enum Keys: CodingKey { - case int, string + case int, string, bool } private static let dddd = "dddd" private func string(for int: Int) -> String { @@ -162,19 +121,15 @@ extension TestCustomEncodeDecode: ExCodable { } } - static let keyMapping: [KeyMap] = [ - KeyMap(\.int, to: Keys.int), - ] - init(from decoder: Decoder) throws { - try decode(from: decoder, with: Self.keyMapping) + try decode(from: decoder, nonnull: false, throws: false) string = decoder[Keys.string] if string == nil || string == Self.dddd { string = string(for: int) } } func encode(to encoder: Encoder) throws { - try encode(to: encoder, with: Self.keyMapping) + try encode(to: encoder, nonnull: false, throws: false) encoder[Keys.string] = Self.dddd } } @@ -309,44 +264,29 @@ struct FloatToBoolDecodingTypeConverter: ExCodableDecodingTypeConverter { } struct TestCustomTypeConverter: Equatable { + @ExCodable("doubleFromBool") var doubleFromBool: Double? = nil } - -extension TestCustomTypeConverter: ExCodable { - - static let keyMapping: [KeyMap] = [ - KeyMap(\.doubleFromBool, to: "doubleFromBool") - ] - - init(from decoder: Decoder) throws { - try decode(from: decoder, with: Self.keyMapping) - } - // func encode(to encoder: Encoder) throws { - // try encode(to: encoder, with: Self.keyMapping) - // } -} +extension TestCustomTypeConverter: ExAutoCodable {} // MARK: class -class TestClass: ExCodable, Equatable { +class TestClass: Codable, Equatable { + @ExCodable("int") var int: Int = 0 + @ExCodable("string") var string: String? = nil init(int: Int, string: String?) { (self.int, self.string) = (int, string) } - static let keyMapping: [KeyMap] = [ - KeyMap(ref: \.int, to: "int"), - KeyMap(ref: \.string, to: "string") - ] - required init(from decoder: Decoder) throws { - try decodeReference(from: decoder, with: Self.keyMapping) + try decode(from: decoder, nonnull: false, throws: false) + } + func encode(to encoder: Encoder) throws { + try encode(to: encoder, nonnull: false, throws: false) } - // func encode(to encoder: Encoder) throws { - // try encode(to: encoder, with: Self.keyMapping) - // } static func == (lhs: TestClass, rhs: TestClass) -> Bool { return lhs.int == rhs.int && lhs.string == rhs.string @@ -356,23 +296,16 @@ class TestClass: ExCodable, Equatable { // MARK: subclass class TestSubclass: TestClass { + + @ExCodable("bool") var bool: Bool = false required init(int: Int, string: String, bool: Bool) { self.bool = bool super.init(int: int, string: string) } - static let keyMappingForTestSubclass: [KeyMap] = [ - KeyMap(ref: \.bool, to: "bool") - ] - required init(from decoder: Decoder) throws { try super.init(from: decoder) - try decodeReference(from: decoder, with: Self.keyMappingForTestSubclass) - } - override func encode(to encoder: Encoder) throws { - try super.encode(to: encoder) - try encode(to: encoder, with: Self.keyMappingForTestSubclass) } static func == (lhs: TestSubclass, rhs: TestSubclass) -> Bool { @@ -385,24 +318,12 @@ class TestSubclass: TestClass { // MARK: ExCodable struct TestExCodable: Equatable { + @ExCodable("int") private(set) var int: Int = 0 - private(set) var string: String? -} - -extension TestExCodable: ExCodable { - - static let keyMapping: [KeyMap] = [ - KeyMap(\.int, to: "int"), - KeyMap(\.string, to: "string") - ] - - init(from decoder: Decoder) throws { - try decode(from: decoder, with: Self.keyMapping) - } - // func encode(to encoder: Encoder) throws { - // try encode(to: encoder, with: Self.keyMapping) - // } + @ExCodable("string") + private(set) var string: String? = nil } +extension TestExCodable: ExAutoCodable {} // MARK: - Tests @@ -457,9 +378,8 @@ final class ExCodableTests: XCTestCase { XCTAssertEqual(copy, test) let localJSON = try! JSONSerialization.jsonObject(with: data) as! [String: Any] XCTAssertEqual(NSDictionary(dictionary: localJSON), [ - "_IS_LOCAL_": true, - "INT": 403, - "STRING": "Forbidden" + "int": 403, + "string": "Forbidden" ]) } else { @@ -487,7 +407,7 @@ final class ExCodableTests: XCTestCase { } func testCustomEncodeDecode() { - let test = TestCustomEncodeDecode(int: 418, string: "I'm a teapot") + let test = TestCustomEncodeDecode(int: 418, string: "I'm a teapot", bool: true) if let data = try? test.encoded() as Data, let copy = try? data.decoded() as TestCustomEncodeDecode { XCTAssertEqual(copy, test) @@ -495,7 +415,8 @@ final class ExCodableTests: XCTestCase { debugPrint(json) XCTAssertEqual(NSDictionary(dictionary: json), [ "int": 418, - "string": "dddd" + "string": "dddd", + "bool": true ]) } else { From 7cc4e52280b6d4d111a1ed05cac54f9a308d1565 Mon Sep 17 00:00:00 2001 From: iwill Date: Fri, 2 Jul 2021 10:38:33 +0800 Subject: [PATCH 03/20] proj: enable build for develop --- .github/workflows/build-and-test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 1cfa351..7f64691 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -2,9 +2,9 @@ name: Build and Test on: push: - branches: [ master ] + branches: [ master, develop ] pull_request: - branches: [ master ] + branches: [ master, develop ] workflow_dispatch: jobs: From 3a921fcaec0a8d84693d6ea869ed5cd78a2d9e70 Mon Sep 17 00:00:00 2001 From: iwill Date: Fri, 2 Jul 2021 16:33:13 +0800 Subject: [PATCH 04/20] sty: coding style --- Sources/ExCodable/ExCodable+DEPRECATED.swift | 3 - Sources/ExCodable/ExCodable.swift | 64 +++++++++++--------- Tests/ExCodableTests/ExCodableTests.swift | 10 +-- 3 files changed, 40 insertions(+), 37 deletions(-) diff --git a/Sources/ExCodable/ExCodable+DEPRECATED.swift b/Sources/ExCodable/ExCodable+DEPRECATED.swift index 7046def..ccb795f 100644 --- a/Sources/ExCodable/ExCodable+DEPRECATED.swift +++ b/Sources/ExCodable/ExCodable+DEPRECATED.swift @@ -18,16 +18,13 @@ public protocol ExCodableProtocol: Codable { @available(*, deprecated) public extension ExCodableProtocol where Root == Self { - // default implementation of ExCodableProtocol static var keyMapping: [KeyMap] { [] } - // default implementation of Encodable func encode(to encoder: Encoder) throws { try encode(to: encoder, with: Self.keyMapping) try encode(to: encoder, nonnull: false, throws: false) } - func decode(from decoder: Decoder) throws { try decode(from: decoder, nonnull: false, throws: false) } diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 4b14cd2..66044f2 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -11,9 +11,15 @@ import Foundation /** * # ExCodable * - * A protocol extends `Encodable` & `Decodable` with `keyMapping` + * - `ExCodable`: A property-wrapper for mapping property to json-key. + * - `ExAutoEncodable` and `ExAutoDecodable`: Protocols with default implementation for Encodable & Decodable. + * - `ExAutoCodable`: A typealias for `ExAutoEncodable & ExAutoDecodable`. + * - Extensions of `Encodable & Decodable`, for encode/decode-ing from internal/external. + * - Extensions of `Encoder & Encoder`, for encode/decode-ing properties one-by-one. + * - Supports alternative-keys, nested-keys and type-conversion + * * <#swift#> <#codable#> <#json#> <#model#> <#type-inference#> - * <#key-mapping#> <#keypath#> <#codingkey#> <#subscript#> + * <#property-wrapper#> <#key-mapping#> <#codingkey#> <#subscript#> * <#alternative-keys#> <#nested-keys#> <#type-conversion#> * * - seealso: [Usage](https://github.com/iwill/ExCodable#usage) from GitGub @@ -70,7 +76,26 @@ extension ExCodable: DecodablePropertyWrapper where Value: Decodable { } } -// MARK: Codable +// MARK: - Auto implementation for Encodable & Decodable + +public protocol ExAutoEncodable: Encodable {} +public extension ExAutoEncodable { + func encode(to encoder: Encoder) throws { + try encode(to: encoder, nonnull: false, throws: false) + } +} + +public protocol ExAutoDecodable: Decodable { init() } +public extension ExAutoDecodable { + init(from decoder: Decoder) throws { + self.init() + try decode(from: decoder, nonnull: false, throws: false) + } +} + +public typealias ExAutoCodable = ExAutoEncodable & ExAutoDecodable + +// MARK: - Encodable & Decodable - internal public extension Encodable { func encode(to encoder: Encoder, nonnull: Bool, throws: Bool) throws { @@ -96,26 +121,7 @@ public extension Decodable { } } -// MARK: auto implementation for Encodable and Decodable - -public protocol ExAutoEncodable: Encodable {} -public extension ExAutoEncodable { - func encode(to encoder: Encoder) throws { - try encode(to: encoder, nonnull: false, throws: false) - } -} - -public protocol ExAutoDecodable: Decodable { init() } -public extension ExAutoDecodable { - init(from decoder: Decoder) throws { - self.init() - try decode(from: decoder, nonnull: false, throws: false) - } -} - -public protocol ExAutoCodable: ExAutoEncodable, ExAutoDecodable {} - -// MARK: - Encoder&Decoder +// MARK: - Encoder & Decoder public extension Encoder { // , abortIfNull nonnull: Bool = false, abortOnError throws: Bool = false subscript(stringKey: String) -> T? { get { return nil } @@ -257,7 +263,7 @@ extension ExCodingKey: CodingKey { public init?(intValue: Int) { self.init(intValue) } } -// MARK: - alternative-keys + nested-keys + type-conversion +// MARK: - KeyedDecodingContainer - alternative-keys + nested-keys + type-conversion fileprivate extension KeyedDecodingContainer { @@ -418,13 +424,13 @@ fileprivate extension KeyedDecodingContainer { else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return String(describing: double) as? T } // include Float } - for conversion in _decodingTypeConverters { - if let value = try? conversion.decode(self, codingKey: codingKey, as: type) { + for converter in _decodingTypeConverters { + if let value = try? converter.decode(self, codingKey: codingKey, as: type) { return value } } - if let custom = self as? ExCodableDecodingTypeConverter, - let value = try? custom.decode(self, codingKey: codingKey, as: type) { + if let customConverter = self as? ExCodableDecodingTypeConverter, + let value = try? customConverter.decode(self, codingKey: codingKey, as: type) { return value } @@ -441,7 +447,7 @@ public func register(_ decodingTypeConverter: ExCodableDecodingTypeConverter) { _decodingTypeConverters.append(decodingTypeConverter) } -// MARK: - Encodable/Decodable +// MARK: - Encodable & Decodable - external // Encodable.encode() -> Data? public extension Encodable { diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index 6f8d2f4..0542f76 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -90,14 +90,14 @@ extension TestNestedKeys: ExAutoCodable {} // MARK: custom encode/decode struct TestCustomEncodeDecode: Equatable { + @ExCodable(Keys.int) var int: Int = 0 + var string: String? - @ExCodable(encode: { encoder, value in - encoder[Keys.bool] = value - }, decode: { decoder in - return decoder[Keys.bool] - }) + + @ExCodable(encode: { encoder, value in encoder[Keys.bool] = value }, + decode: { decoder in return decoder[Keys.bool] }) var bool: Bool = false } From 1cbc79f63091383cd8fa76f165361166ab80f64c Mon Sep 17 00:00:00 2001 From: "Mr. Ming" Date: Mon, 16 Aug 2021 16:56:19 +0800 Subject: [PATCH 05/20] sty: comments & readme --- README.md | 7 +++++-- Sources/ExCodable/ExCodable.swift | 23 +++++++++++------------ 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 0154806..b9fce2b 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,12 @@ [![Swift 5.0](https://img.shields.io/badge/Swift-5.0-orange.svg)](https://swift.org/) [![Swift Package Manager](https://img.shields.io/badge/spm-compatible-brightgreen.svg?style=flat)](https://swift.org/package-manager/) [![Platforms](https://img.shields.io/cocoapods/p/ExCodable.svg)](#readme) +
[![Build and Test](https://github.com/iwill/ExCodable/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/iwill/ExCodable/actions/workflows/build-and-test.yml) [![GitHub Releases (latest SemVer)](https://img.shields.io/github/v/release/iwill/ExCodable.svg?sort=semver)](https://github.com/iwill/ExCodable/releases) [![Deploy to CocoaPods](https://github.com/iwill/ExCodable/actions/workflows/deploy_to_cocoapods.yml/badge.svg)](https://github.com/iwill/ExCodable/actions/workflows/deploy_to_cocoapods.yml) [![Cocoapods](https://img.shields.io/cocoapods/v/ExCodable.svg)](https://cocoapods.org/pods/ExCodable) +
[![LICENSE](https://img.shields.io/github/license/iwill/ExCodable.svg)](https://github.com/iwill/ExCodable/blob/master/LICENSE) [![@minglq](https://img.shields.io/twitter/url?url=https%3A%2F%2Fgithub.com%2Fiwill%2FExCodable)](https://twitter.com/minglq) @@ -17,6 +19,7 @@ En | [中文](https://iwill.im/ExCodable/) - [Features](#features) - [Usage](#usage) - [Requirements](#requirements) +- [Migration Guides](#migration-guides) - [Installation](#installation) - [Credits](#credits) - [License](#license) @@ -24,7 +27,7 @@ En | [中文](https://iwill.im/ExCodable/) ## Features - Extends Swift `Codable` - `Encodable & Decodable`; -- Supports Key-Mapping via `KeyPath` and Coding-Key: +- Supports Key-Mapping via Property-Wrapper `ExCodable` + `String`: - `ExCodable` did not read/write memory via unsafe pointers; - No need to encode/decode properties one by one; - Just requires using `var` to declare properties and provide default values; @@ -57,7 +60,7 @@ struct TestAutoCodable: Codable, Equatable { ``` -But, if you have to encode/decode manually for some reason, e.g. Alternative-Keys and Nested-Keys ... +But, if you have to encode/decode manually for some reason, e.g. Default-Value, Alternative-Keys, Nested-Keys or Type-Conversions ... ```swift struct TestManualCodable: Equatable { diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 66044f2..3fe5912 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -11,20 +11,20 @@ import Foundation /** * # ExCodable * - * - `ExCodable`: A property-wrapper for mapping property to json-key. - * - `ExAutoEncodable` and `ExAutoDecodable`: Protocols with default implementation for Encodable & Decodable. + * - `ExCodable`: A property-wrapper for mapping properties to JSON keys. + * - `ExAutoEncodable` & `ExAutoDecodable`: Protocols with default implementation for Encodable & Decodable. * - `ExAutoCodable`: A typealias for `ExAutoEncodable & ExAutoDecodable`. - * - Extensions of `Encodable & Decodable`, for encode/decode-ing from internal/external. - * - Extensions of `Encoder & Encoder`, for encode/decode-ing properties one-by-one. - * - Supports alternative-keys, nested-keys and type-conversion + * - `Encodable` & `Decodable` extensions for encode/decode-ing from internal/external. + * - `Encoder` & `Encoder` extensions for encode/decode-ing properties one by one. + * - Supports Alternative-Keys, Nested-Keys, Type-Conversions and Default-Values. * * <#swift#> <#codable#> <#json#> <#model#> <#type-inference#> - * <#property-wrapper#> <#key-mapping#> <#codingkey#> <#subscript#> - * <#alternative-keys#> <#nested-keys#> <#type-conversion#> + * <#key-mapping#> <#property-wrapper#> <#coding-key#> <#subscript#> + * <#alternative-keys#> <#nested-keys#> <#type-conversions#> * - * - seealso: [Usage](https://github.com/iwill/ExCodable#usage) from GitGub - * - seealso: `ExCodableTests.swift` form the source code - * - seealso: Idea from [Decoding and overriding](https://www.swiftbysundell.com/articles/property-wrappers-in-swift/#decoding-and-overriding), by John Sundell. + * - seealso: [Usage](https://github.com/iwill/ExCodable#usage) from the `README.md` + * - seealso: `ExCodableTests.swift` from the `Tests` + * - seealso: [Decoding and overriding](https://www.swiftbysundell.com/articles/property-wrappers-in-swift/#decoding-and-overriding) and [Useful Codable extensions](https://www.swiftbysundell.com/tips/useful-codable-extensions/), by John Sundell. */ @propertyWrapper @@ -59,7 +59,6 @@ extension ExCodable: EncodablePropertyWrapper where Value: Encodable { fileprivate func encode(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws { if encode != nil { try encode!(encoder, wrappedValue) } else { try encoder.encode(wrappedValue, for: stringKeys?.first ?? String(label), nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`) } - } } @@ -263,7 +262,7 @@ extension ExCodingKey: CodingKey { public init?(intValue: Int) { self.init(intValue) } } -// MARK: - KeyedDecodingContainer - alternative-keys + nested-keys + type-conversion +// MARK: - KeyedDecodingContainer - alternative-keys + nested-keys + type-conversions fileprivate extension KeyedDecodingContainer { From de7692c8e37a57db93d1aed40bc7ab88a413fb9b Mon Sep 17 00:00:00 2001 From: iwill Date: Fri, 4 Feb 2022 15:23:37 +0800 Subject: [PATCH 06/20] opt: type inference in test --- Tests/ExCodableTests/ExCodableTests.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index 0542f76..fa59bf7 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -333,7 +333,7 @@ final class ExCodableTests: XCTestCase { let test = TestAutoCodable(int: 100, string: "Continue") if let data = try? test.encoded() as Data, let copy = try? data.decoded() as TestAutoCodable, - let json: [String: Any] = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { XCTAssertEqual(copy, test) XCTAssertEqual(NSDictionary(dictionary: json), ["i": 100, "s": "Continue"]) } From 417575fd04cb01f8dc2e9cebe20bf702c9621634 Mon Sep 17 00:00:00 2001 From: iwill Date: Fri, 4 Mar 2022 01:05:30 +0800 Subject: [PATCH 07/20] opt: test --- Tests/ExCodableTests/ExCodableTests.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index fa59bf7..4245be9 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -82,7 +82,7 @@ extension TestAlternativeKeys: ExAutoCodable {} struct TestNestedKeys: Equatable { @ExCodable var int: Int = 0 - @ExCodable("nested.string") + @ExCodable("nested.nested.string") var string: String! = nil } extension TestNestedKeys: ExAutoCodable {} @@ -397,7 +397,9 @@ final class ExCodableTests: XCTestCase { XCTAssertEqual(NSDictionary(dictionary: json), [ "int": 404, "nested": [ - "string": "Not Found" + "nested": [ + "string": "Not Found" + ] ] ]) } From 31c4a3404757a1292b7d576817cb5483e2081361 Mon Sep 17 00:00:00 2001 From: iwill Date: Fri, 4 Mar 2022 01:07:37 +0800 Subject: [PATCH 08/20] =?UTF-8?q?opt:=20Mr.=20Ming=20>=20Mr.=20M=C3=ADng?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ExCodable.podspec | 2 +- LICENSE | 2 +- Sources/ExCodable/ExCodable+DEPRECATED.swift | 4 ++-- Sources/ExCodable/ExCodable.swift | 4 ++-- Tests/ExCodableTests/ExCodableTests.swift | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ExCodable.podspec b/ExCodable.podspec index fa839ab..336bd9c 100644 --- a/ExCodable.podspec +++ b/ExCodable.podspec @@ -10,7 +10,7 @@ Pod::Spec.new do |s| # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # s.license = "MIT" - s.author = { "Mr. Ming" => "i+ExCodable@iwill.im" } + s.author = { "Mr. Míng" => "i+ExCodable@iwill.im" } s.social_media_url = "https://iwill.im/about/" # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # diff --git a/LICENSE b/LICENSE index f66b212..2c34e9a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2021 Mr. Ming +Copyright (c) 2021 Mr. Míng Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Sources/ExCodable/ExCodable+DEPRECATED.swift b/Sources/ExCodable/ExCodable+DEPRECATED.swift index ccb795f..8efb99b 100644 --- a/Sources/ExCodable/ExCodable+DEPRECATED.swift +++ b/Sources/ExCodable/ExCodable+DEPRECATED.swift @@ -2,8 +2,8 @@ // ExCodable.swift // ExCodable // -// Created by Mr. Ming on 2021-07-01. -// Copyright (c) 2021 Mr. Ming . Released under the MIT license. +// Created by Mr. Míng on 2021-07-01. +// Copyright (c) 2021 Mr. Míng . Released under the MIT license. // import Foundation diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 3fe5912..0529899 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -2,8 +2,8 @@ // ExCodable.swift // ExCodable // -// Created by Mr. Ming on 2021-02-10. -// Copyright (c) 2021 Mr. Ming . Released under the MIT license. +// Created by Mr. Míng on 2021-02-10. +// Copyright (c) 2021 Mr. Míng . Released under the MIT license. // import Foundation diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index 4245be9..5e47bcc 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -2,8 +2,8 @@ // ExCodableTests.swift // ExCodable // -// Created by Mr. Ming on 2021-02-10. -// Copyright (c) 2021 Mr. Ming . Released under the MIT license. +// Created by Mr. Míng on 2021-02-10. +// Copyright (c) 2021 Mr. Míng . Released under the MIT license. // import XCTest From 527c2ff5919d17d3a1675c090e34fc121a035f0d Mon Sep 17 00:00:00 2001 From: iwill Date: Fri, 4 Mar 2022 01:08:41 +0800 Subject: [PATCH 09/20] proj: copyright --- LICENSE | 2 +- Sources/ExCodable/ExCodable+DEPRECATED.swift | 2 +- Sources/ExCodable/ExCodable.swift | 2 +- Tests/ExCodableTests/ExCodableTests.swift | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/LICENSE b/LICENSE index 2c34e9a..d4a2b48 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2021 Mr. Míng +Copyright (c) 2022 Mr. Míng Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Sources/ExCodable/ExCodable+DEPRECATED.swift b/Sources/ExCodable/ExCodable+DEPRECATED.swift index 8efb99b..4cd2657 100644 --- a/Sources/ExCodable/ExCodable+DEPRECATED.swift +++ b/Sources/ExCodable/ExCodable+DEPRECATED.swift @@ -3,7 +3,7 @@ // ExCodable // // Created by Mr. Míng on 2021-07-01. -// Copyright (c) 2021 Mr. Míng . Released under the MIT license. +// Copyright (c) 2022 Mr. Míng . Released under the MIT license. // import Foundation diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 0529899..7f40e4c 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -3,7 +3,7 @@ // ExCodable // // Created by Mr. Míng on 2021-02-10. -// Copyright (c) 2021 Mr. Míng . Released under the MIT license. +// Copyright (c) 2022 Mr. Míng . Released under the MIT license. // import Foundation diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index 5e47bcc..13f57d5 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -3,7 +3,7 @@ // ExCodable // // Created by Mr. Míng on 2021-02-10. -// Copyright (c) 2021 Mr. Míng . Released under the MIT license. +// Copyright (c) 2022 Mr. Míng . Released under the MIT license. // import XCTest From 8905d31c2965a126af78d39fac237797efa76058 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=ADng?= Date: Wed, 1 Jun 2022 15:38:09 +0800 Subject: [PATCH 10/20] fix: #5 print `wrappedValue` instead of `ExCodable` --- Sources/ExCodable/ExCodable.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 7f40e4c..3cdde7f 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -51,6 +51,10 @@ extension ExCodable: Equatable where Value: Equatable { return lhs.wrappedValue == rhs.wrappedValue } } +extension ExCodable: CustomStringConvertible { // CustomDebugStringConvertible + public var description: String { String(describing: wrappedValue) } + // public var debugDescription: String { "\(type(of: self))(\(wrappedValue))" } +} fileprivate protocol EncodablePropertyWrapper { func encode(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws From 30faae3a0d4b87a8031a05a1e655cd13ea076694 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=CC=81ng?= Date: Mon, 23 Oct 2023 18:43:23 +0800 Subject: [PATCH 11/20] opt: code and test --- Sources/ExCodable/ExCodable+DEPRECATED.swift | 4 +-- Sources/ExCodable/ExCodable.swift | 15 ++++++----- Tests/ExCodableTests/ExCodableTests.swift | 27 ++++++++++++++------ 3 files changed, 29 insertions(+), 17 deletions(-) diff --git a/Sources/ExCodable/ExCodable+DEPRECATED.swift b/Sources/ExCodable/ExCodable+DEPRECATED.swift index 4cd2657..c23e974 100644 --- a/Sources/ExCodable/ExCodable+DEPRECATED.swift +++ b/Sources/ExCodable/ExCodable+DEPRECATED.swift @@ -10,7 +10,7 @@ import Foundation // MARK: - keyMapping -@available(*, deprecated, message: "use `@ExCodable` property wrapper instead") +@available(*, deprecated, message: "Use `@ExCodable` property wrapper instead.") public protocol ExCodableProtocol: Codable { associatedtype Root = Self where Root: ExCodableProtocol static var keyMapping: [KeyMap] { get } @@ -43,7 +43,7 @@ public extension ExCodableProtocol { } } -@available(*, deprecated, message: "use `@ExCodable` property wrapper instead") +@available(*, deprecated, message: "Use `@ExCodable` property wrapper instead.") public final class KeyMap { fileprivate let encode: (_ root: Root, _ encoder: Encoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void fileprivate let decode: ((_ root: inout Root, _ decoder: Decoder, _ nonnullAll: Bool, _ throwsAll: Bool) throws -> Void)? diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 3cdde7f..00a1da0 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -24,7 +24,8 @@ import Foundation * * - seealso: [Usage](https://github.com/iwill/ExCodable#usage) from the `README.md` * - seealso: `ExCodableTests.swift` from the `Tests` - * - seealso: [Decoding and overriding](https://www.swiftbysundell.com/articles/property-wrappers-in-swift/#decoding-and-overriding) and [Useful Codable extensions](https://www.swiftbysundell.com/tips/useful-codable-extensions/), by John Sundell. + * - seealso: [Decoding and overriding](https://www.swiftbysundell.com/articles/property-wrappers-in-swift/#decoding-and-overriding) + * and [Useful Codable extensions](https://www.swiftbysundell.com/tips/useful-codable-extensions/), by John Sundell. */ @propertyWrapper @@ -71,9 +72,9 @@ fileprivate protocol DecodablePropertyWrapper { } extension ExCodable: DecodablePropertyWrapper where Value: Decodable { fileprivate func decode(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool) throws { - if let value = decode != nil - ? try decode!(decoder) - : try decoder.decode(stringKeys ?? [String(label)], nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`) { + if let value = (decode != nil + ? try decode!(decoder) + : try decoder.decode(stringKeys ?? [String(label)], nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`)) { wrappedValue = value } } @@ -330,9 +331,9 @@ fileprivate extension KeyedDecodingContainer { var firstError: Error? do { - if let value = nonnull - ? (`throws` ? try decode(type, forKey: codingKey) : try? decode(type, forKey: codingKey)) - : (`throws` ? try decodeIfPresent(type, forKey: codingKey) : try? decodeIfPresent(type, forKey: codingKey)) { + if let value = (nonnull + ? (`throws` ? try decode(type, forKey: codingKey) : try? decode(type, forKey: codingKey)) + : (`throws` ? try decodeIfPresent(type, forKey: codingKey) : try? decodeIfPresent(type, forKey: codingKey))) { return value } } diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index 13f57d5..f4d9ae7 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -94,7 +94,9 @@ struct TestCustomEncodeDecode: Equatable { @ExCodable(Keys.int) var int: Int = 0 - var string: String? + @ExCodable(encode: { encoder, value in encoder["nested.nested.string"] = value }, + decode: { decoder in return decoder["nested.nested.string"] }) + var string: String? = nil @ExCodable(encode: { encoder, value in encoder[Keys.bool] = value }, decode: { decoder in return decoder[Keys.bool] }) @@ -104,7 +106,7 @@ struct TestCustomEncodeDecode: Equatable { extension TestCustomEncodeDecode: Codable { private enum Keys: CodingKey { - case int, string, bool + case int, bool } private static let dddd = "dddd" private func string(for int: Int) -> String { @@ -123,14 +125,14 @@ extension TestCustomEncodeDecode: Codable { init(from decoder: Decoder) throws { try decode(from: decoder, nonnull: false, throws: false) - string = decoder[Keys.string] + string = decoder["nested.nested.string"] if string == nil || string == Self.dddd { string = string(for: int) } } func encode(to encoder: Encoder) throws { try encode(to: encoder, nonnull: false, throws: false) - encoder[Keys.string] = Self.dddd + encoder["nested.nested.string"] = Self.dddd } } @@ -309,9 +311,9 @@ class TestSubclass: TestClass { } static func == (lhs: TestSubclass, rhs: TestSubclass) -> Bool { - return lhs.int == rhs.int - && lhs.string == rhs.string - && lhs.bool == rhs.bool + return (lhs.int == rhs.int + && lhs.string == rhs.string + && lhs.bool == rhs.bool) } } @@ -363,6 +365,11 @@ final class ExCodableTests: XCTestCase { let copy2 = try? TestStruct.decoded(from: data) { XCTAssertEqual(copy1, test) XCTAssertEqual(copy2, test) + + let string = "string: \(test)" + print(string) + print(test) + debugPrint(test) } else { XCTFail() @@ -417,7 +424,11 @@ final class ExCodableTests: XCTestCase { debugPrint(json) XCTAssertEqual(NSDictionary(dictionary: json), [ "int": 418, - "string": "dddd", + "nested": [ + "nested": [ + "string": "dddd" + ] + ], "bool": true ]) } From 74ba8ab25b0aa2b9f50c75011d0a938550508ac6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=CC=81ng?= Date: Mon, 23 Oct 2023 18:53:17 +0800 Subject: [PATCH 12/20] meta: readme --- README.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index b9fce2b..b8b4d0d 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ En | [中文](https://iwill.im/ExCodable/) ## Features - Extends Swift `Codable` - `Encodable & Decodable`; -- Supports Key-Mapping via Property-Wrapper `ExCodable` + `String`: +- Supports Key-Mapping via **Property-Wrapper** `ExCodable` + `String`: - `ExCodable` did not read/write memory via unsafe pointers; - No need to encode/decode properties one by one; - Just requires using `var` to declare properties and provide default values; @@ -45,7 +45,9 @@ En | [中文](https://iwill.im/ExCodable/) ## Usage -### 0. `Codable`: +### 0. ⭐️ Star this repo 🤭 + +### 1. `Codable`: With `Codable`, it just needs to adop the `Codable` protocol without implementing any method of it. @@ -118,7 +120,7 @@ extension TestExCodable: ExCodable { ``` -### 1. Key-Mapping for `struct`: +### 2. Key-Mapping for `struct`: With `ExCodable`, it needs to to declare properties with `var` and provide default values. @@ -150,7 +152,7 @@ extension TestStruct: ExCodable { ``` -### 2. Alternative-Keys: +### 3. Alternative-Keys: ```swift static let keyMapping: [KeyMap] = [ @@ -160,7 +162,7 @@ static let keyMapping: [KeyMap] = [ ``` -### 3. Nested-Keys: +### 4. Nested-Keys: ```swift static let keyMapping: [KeyMap] = [ @@ -170,7 +172,7 @@ static let keyMapping: [KeyMap] = [ ``` -### 4. Custom encode/decode: +### 5. Custom encode/decode: ```swift struct TestCustomEncodeDecode: Equatable { @@ -220,7 +222,7 @@ extension TestCustomEncodeDecode: ExCodable { ``` -### 5. Encode/decode constant properties with subscripts: +### 6. Encode/decode constant properties with subscripts: Using `let` to declare properties without default values. @@ -259,7 +261,7 @@ extension TestSubscript: Encodable, Decodable { ``` -### 6. Custom Type-Conversions: +### 7. Custom Type-Conversions: Declare struct `FloatToBoolDecodingTypeConverter` with protocol `ExCodableDecodingTypeConverter` and implement its method, decode values in alternative types and convert to target type: @@ -291,7 +293,7 @@ Register `FloatToBoolDecodingTypeConverter` with an instance: register(FloatToBoolDecodingTypeConverter()) ``` -### 7. Key-Mapping for `class`: +### 8. Key-Mapping for `class`: Cannot adopt `ExCodable` in extension of classes. @@ -320,7 +322,7 @@ class TestClass: ExCodable, Equatable { ``` -### 8. Key-Mapping for subclass: +### 9. Key-Mapping for subclass: Requires declaring another static Key-Mapping for subclass. @@ -354,7 +356,7 @@ class TestSubclass: TestClass { ``` -### 9. Encode/decode with Type-Inference: +### 10. Encode/decode with Type-Inference: ```swift let test = TestStruct(int: 304, string: "Not Modified") @@ -428,7 +430,7 @@ Hope you like this project, don't forget to give it a star [⭐](https://github. ## Connect with me -- Mr. Míng ([@iwill](https://github.com/iwill)) | i+ExCodable@iwill.im +- Míng ([@iwill](https://github.com/iwill)) | i+ExCodable@iwill.im ## License From a4622b5255f0a22ceb92c869f0c1d27a84314d3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=CC=81ng?= Date: Mon, 23 Oct 2023 18:58:34 +0800 Subject: [PATCH 13/20] meta: copyright --- ExCodable.podspec | 2 +- LICENSE | 2 +- Sources/ExCodable/ExCodable+DEPRECATED.swift | 4 ++-- Sources/ExCodable/ExCodable.swift | 4 ++-- Tests/ExCodableTests/ExCodableTests.swift | 4 ++-- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/ExCodable.podspec b/ExCodable.podspec index 336bd9c..47caea5 100644 --- a/ExCodable.podspec +++ b/ExCodable.podspec @@ -10,7 +10,7 @@ Pod::Spec.new do |s| # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # s.license = "MIT" - s.author = { "Mr. Míng" => "i+ExCodable@iwill.im" } + s.author = { "Míng" => "i+ExCodable@iwill.im" } s.social_media_url = "https://iwill.im/about/" # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # diff --git a/LICENSE b/LICENSE index d4a2b48..0977b98 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2022 Mr. Míng +Copyright (c) 2023 Míng Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/Sources/ExCodable/ExCodable+DEPRECATED.swift b/Sources/ExCodable/ExCodable+DEPRECATED.swift index c23e974..c686bfe 100644 --- a/Sources/ExCodable/ExCodable+DEPRECATED.swift +++ b/Sources/ExCodable/ExCodable+DEPRECATED.swift @@ -2,8 +2,8 @@ // ExCodable.swift // ExCodable // -// Created by Mr. Míng on 2021-07-01. -// Copyright (c) 2022 Mr. Míng . Released under the MIT license. +// Created by Míng on 2021-07-01. +// Copyright (c) 2023 Míng . Released under the MIT license. // import Foundation diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 00a1da0..9c6402d 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -2,8 +2,8 @@ // ExCodable.swift // ExCodable // -// Created by Mr. Míng on 2021-02-10. -// Copyright (c) 2022 Mr. Míng . Released under the MIT license. +// Created by Míng on 2021-02-10. +// Copyright (c) 2023 Míng . Released under the MIT license. // import Foundation diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index f4d9ae7..ea9fac8 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -2,8 +2,8 @@ // ExCodableTests.swift // ExCodable // -// Created by Mr. Míng on 2021-02-10. -// Copyright (c) 2022 Mr. Míng . Released under the MIT license. +// Created by Míng on 2021-02-10. +// Copyright (c) 2023 Míng . Released under the MIT license. // import XCTest From b38d5c5277ef541ba43fcedcc8ff3a0d1a69e0a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=CC=81ng?= Date: Thu, 26 Oct 2023 00:50:19 +0800 Subject: [PATCH 14/20] meta: version 1.0.0 --- ExCodable.podspec | 2 +- README.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ExCodable.podspec b/ExCodable.podspec index 47caea5..ec802c7 100644 --- a/ExCodable.podspec +++ b/ExCodable.podspec @@ -3,7 +3,7 @@ Pod::Spec.new do |s| # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # s.name = "ExCodable" # export LIB_VERSION=$(git describe --tags `git rev-list --tags --max-count=1`) - s.version = ENV["LIB_VERSION"] || "1.0.0-alpha" + s.version = ENV["LIB_VERSION"] || "1.0.0" s.summary = "Key-Mapping Extensions for Swift Codable" # s.description = "Key-Mapping Extensions for Swift Codable." s.homepage = "https://github.com/iwill/ExCodable" diff --git a/README.md b/README.md index b8b4d0d..a23e25b 100644 --- a/README.md +++ b/README.md @@ -379,14 +379,14 @@ XCTAssertEqual(copy2, test) - [Swift Package Manager](https://swift.org/package-manager/): ```swift -.package(url: "https://github.com/iwill/ExCodable", from: "0.6.0") +.package(url: "https://github.com/iwill/ExCodable", from: "1.0.0") ``` - [CocoaPods](http://cocoapods.org): ```ruby -pod 'ExCodable', '~> 0.6.0' +pod 'ExCodable', '~> 1.0.0' ``` From e7ae8e03a4c10dadd31f38ce4723563b37e31f3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=CC=81ng?= Date: Thu, 26 Oct 2023 10:57:48 +0800 Subject: [PATCH 15/20] meta: doc for 1.0 --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a23e25b..570e133 100644 --- a/README.md +++ b/README.md @@ -45,11 +45,13 @@ En | [中文](https://iwill.im/ExCodable/) ## Usage -### 0. ⭐️ Star this repo 🤭 +### 0. Star this repo ⭐️ -### 1. `Codable`: +🤭 -With `Codable`, it just needs to adop the `Codable` protocol without implementing any method of it. +### 1. `Codable` vs `ExCodable`: + +With `Codable`, it just needs to adopt the `Codable` protocol without implementing any method of it. ```swift struct TestAutoCodable: Codable, Equatable { @@ -393,7 +395,7 @@ pod 'ExCodable', '~> 1.0.0' - Code Snippets: > Title: ExCodable -> Summary: Adopte to ExCodable protocol +> Summary: Adopt to ExCodable protocol > Language: Swift > Platform: All > Completion: ExCodable From 8c9e501a0c86cf39ea667378d5f95d34150826a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=CC=81ng?= Date: Fri, 15 Dec 2023 15:32:22 +0800 Subject: [PATCH 16/20] fea: update swift and platform versions, fix warning, update tests --- ExCodable.podspec | 5 +++++ Package.swift | 16 ++++++++-------- Tests/ExCodableTests/ExCodableTests.swift | 16 ---------------- Tests/ExCodableTests/XCTestManifests.swift | 9 --------- Tests/LinuxMain.swift | 7 ------- 5 files changed, 13 insertions(+), 40 deletions(-) delete mode 100644 Tests/ExCodableTests/XCTestManifests.swift delete mode 100644 Tests/LinuxMain.swift diff --git a/ExCodable.podspec b/ExCodable.podspec index ec802c7..43d4142 100644 --- a/ExCodable.podspec +++ b/ExCodable.podspec @@ -43,4 +43,9 @@ Pod::Spec.new do |s| # s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } # s.dependency "pod", "~> 1.0.0" + # use <"> but not <'> for #{s.name} and #{s.version} + s.pod_target_xcconfig = { + "OTHER_SWIFT_FLAGS" => "$(inherited) -Xfrontend -module-interface-preserve-types-as-written", + } + end diff --git a/Package.swift b/Package.swift index 0f9b40c..27c2d88 100644 --- a/Package.swift +++ b/Package.swift @@ -1,19 +1,19 @@ -// swift-tools-version:5.3 +// swift-tools-version:5.9 import PackageDescription let package = Package( name: "ExCodable", platforms: [ - .iOS(.v9), - .tvOS(.v9), - .macOS(.v10_10), - .watchOS(.v2) + .iOS(.v12), + .tvOS(.v12), + .macOS(.v10_13), + .watchOS(.v4) ], products: [ - .library( - name: "ExCodable", - targets: ["ExCodable"]), + .library(name: "ExCodable", targets: ["ExCodable"]), + // .library(name: "ExCodable-Static", type: .static, targets: ["ExCodable"]), + .library(name: "ExCodable-Dynamic", type: .dynamic, targets: ["ExCodable"]) ], dependencies: [ // .package(url: "https://github.com/user/repo", from: "1.0.0") diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index ea9fac8..ebfe97f 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -682,20 +682,4 @@ final class ExCodableTests: XCTestCase { let milliseconds = elapsed / 1_000_000 print("elapsed: \(milliseconds) ms") } - - static var allTests = [ - ("testAutoCodable", testAutoCodable), - ("testManualCodable", testManualCodable), - ("testStruct", testStruct), - ("testAlternativeKeys", testAlternativeKeys), - ("testNestedKeys", testNestedKeys), - ("testCustomEncodeDecode", testCustomEncodeDecode), - ("testSubscript", testSubscript), - ("testTypeConversions", testTypeConversions), - ("testCustomTypeConverter", testCustomTypeConverter), - ("testClass", testClass), - ("testSubclass", testSubclass), - ("testExCodable", testExCodable), - ("testElapsed", testElapsed) - ] } diff --git a/Tests/ExCodableTests/XCTestManifests.swift b/Tests/ExCodableTests/XCTestManifests.swift deleted file mode 100644 index d608652..0000000 --- a/Tests/ExCodableTests/XCTestManifests.swift +++ /dev/null @@ -1,9 +0,0 @@ -import XCTest - -#if !canImport(ObjectiveC) -public func allTests() -> [XCTestCaseEntry] { - return [ - testCase(ExCodableTests.allTests), - ] -} -#endif diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift deleted file mode 100644 index 863417c..0000000 --- a/Tests/LinuxMain.swift +++ /dev/null @@ -1,7 +0,0 @@ -import XCTest - -import ExCodableTests - -var tests = [XCTestCaseEntry]() -tests += ExCodableTests.allTests() -XCTMain(tests) From 3bad8372d8c3de6f670598be109584a06342a3d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=CC=81ng?= Date: Tue, 23 Jan 2024 04:24:58 +0800 Subject: [PATCH 17/20] fix/opt: not to encode nil if not nonnull --- ExCodable.podspec | 2 +- Sources/ExCodable/ExCodable.swift | 26 +++++++++++++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/ExCodable.podspec b/ExCodable.podspec index 43d4142..1cb4459 100644 --- a/ExCodable.podspec +++ b/ExCodable.podspec @@ -18,7 +18,7 @@ Pod::Spec.new do |s| s.tvos.deployment_target = "9.0" s.osx.deployment_target = "10.10" s.watchos.deployment_target = "2.0" - s.swift_version = "5.0" + s.swift_version = "5.9" # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # s.source = { :git => "https://github.com/iwill/ExCodable.git", :tag => s.version.to_s } diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 9c6402d..5341745 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -63,7 +63,12 @@ fileprivate protocol EncodablePropertyWrapper { extension ExCodable: EncodablePropertyWrapper where Value: Encodable { fileprivate func encode(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws { if encode != nil { try encode!(encoder, wrappedValue) } - else { try encoder.encode(wrappedValue, for: stringKeys?.first ?? String(label), nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`) } + else { + let value = deepUnwrap(wrappedValue) + if value != nil || self.nonnull ?? nonnull { + try encoder.encode(wrappedValue, for: stringKeys?.first ?? String(label), nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`) + } + } } } @@ -530,3 +535,22 @@ extension JSONDecoder: DataDecoder {} extension PropertyListEncoder: DataEncoder {} @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension PropertyListDecoder: DataDecoder {} + +// MARK: Optional + +private protocol OptionalProtocol { + var deepWrapped: Any? { get } +} +extension Optional: OptionalProtocol { + var deepWrapped: Any? { + guard case let .some(wrapped) = self else { return nil } + guard let wrapped = wrapped as? OptionalProtocol else { return wrapped } + return wrapped.deepWrapped + } +} +private func deepUnwrap(_ any: Any) -> Any? { + if let any = any as? OptionalProtocol { + return any.deepWrapped + } + return any +} From 85c8786c0dda2bfdec1682864da37f6ba2121b5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=ADng?= Date: Wed, 24 Jan 2024 11:22:35 +0800 Subject: [PATCH 18/20] Update build-and-test.yml update Swift version to 5.9 --- .github/workflows/build-and-test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 7f64691..b4471cb 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -11,7 +11,8 @@ jobs: build: runs-on: macos-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 + - uses: swift-actions/setup-swift@v1 - name: Build run: swift build -v - name: Run tests From 35c4be72e03bd17b3d92f4c7395161b964bba7e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=CC=81ng?= Date: Thu, 25 Apr 2024 04:16:53 +0800 Subject: [PATCH 19/20] meta: swift version and opt for package --- Package.swift | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/Package.swift b/Package.swift index 27c2d88..10a6f7a 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.9 +// swift-tools-version:5.10 import PackageDescription @@ -19,12 +19,8 @@ let package = Package( // .package(url: "https://github.com/user/repo", from: "1.0.0") ], targets: [ - .target( - name: "ExCodable", - dependencies: []), - .testTarget( - name: "ExCodableTests", - dependencies: ["ExCodable"]), + .target(name: "ExCodable", dependencies: []), + .testTarget(name: "ExCodableTests", dependencies: ["ExCodable"]) ], swiftLanguageVersions: [.v5] ) From 2240d743c5716dabe71db7cb5a200eca114b15dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mi=CC=81ng?= Date: Thu, 25 Apr 2024 04:18:45 +0800 Subject: [PATCH 20/20] fea: try to support enum x: RawRepresentable --- README.md | 56 +++++- Sources/ExCodable/ExCodable.swift | 219 +++++++++++++++------- Tests/ExCodableTests/ExCodableTests.swift | 141 ++++++++++---- 3 files changed, 305 insertions(+), 111 deletions(-) diff --git a/README.md b/README.md index 570e133..ce0792f 100644 --- a/README.md +++ b/README.md @@ -265,11 +265,11 @@ extension TestSubscript: Encodable, Decodable { ### 7. Custom Type-Conversions: -Declare struct `FloatToBoolDecodingTypeConverter` with protocol `ExCodableDecodingTypeConverter` and implement its method, decode values in alternative types and convert to target type: +A. For a specific type: ```swift -struct FloatToBoolDecodingTypeConverter: ExCodableDecodingTypeConverter { - public func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { +extension TestTypeConverter: ExCodableDecodingTypeConverter { + public static func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { // Bool -> Double if type is Double.Type || type is Double?.Type { if let bool = try? container.decodeIfPresent(Bool.self, forKey: codingKey) { @@ -289,10 +289,56 @@ struct FloatToBoolDecodingTypeConverter: ExCodableDecodingTypeConverter { ``` -Register `FloatToBoolDecodingTypeConverter` with an instance: +B. For multiple types: ```swift -register(FloatToBoolDecodingTypeConverter()) +extension ExCodableDecodingTypeConverter { + public static func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { + // Bool -> Double + if type is Double.Type || type is Double?.Type { + if let bool = try? container.decodeIfPresent(Bool.self, forKey: codingKey) { + return (bool ? 1.0 : 0.0) as? T + } + } + // Bool -> Float + else if type is Float.Type || type is Float?.Type { + if let bool = try? container.decodeIfPresent(Bool.self, forKey: codingKey) { + return (bool ? 1.0 : 0.0) as? T + } + } + // Double or Float NOT found + return nil + } +} + +extension TestTypeConverter001: ExCodableDecodingTypeConverter {} +extension TestTypeConverter002: ExCodableDecodingTypeConverter {} +extension TestTypeConverter003: ExCodableDecodingTypeConverter {} + +``` + +C. For all types - DONOT do this in public frameworks: + +```swift +extension KeyedDecodingContainer: ExCodableDecodingTypeConverter { + public static func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { + // Bool -> Double + if type is Double.Type || type is Double?.Type { + if let bool = try? container.decodeIfPresent(Bool.self, forKey: codingKey) { + return (bool ? 1.0 : 0.0) as? T + } + } + // Bool -> Float + else if type is Float.Type || type is Float?.Type { + if let bool = try? container.decodeIfPresent(Bool.self, forKey: codingKey) { + return (bool ? 1.0 : 0.0) as? T + } + } + // Double or Float NOT found + return nil + } +} + ``` ### 8. Key-Mapping for `class`: diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 5341745..51b4efc 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -34,17 +34,17 @@ public final class ExCodable { fileprivate let nonnull, `throws`: Bool? fileprivate let encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)?, decode: ((_ decoder: Decoder) throws -> Value?)? public var wrappedValue: Value - private init(wrappedValue: Value, stringKeys: [String]? = nil, nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)?, decode: ((_ decoder: Decoder) throws -> Value?)?) { - (self.wrappedValue, self.stringKeys, self.nonnull, self.throws, self.encode, self.decode) = (wrappedValue, stringKeys, nonnull, `throws`, encode, decode) + private init(wrappedValue initialValue: Value, stringKeys: [String]? = nil, nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)?, decode: ((_ decoder: Decoder) throws -> Value?)?) { + (self.wrappedValue, self.stringKeys, self.nonnull, self.throws, self.encode, self.decode) = (initialValue, stringKeys, nonnull, `throws`, encode, decode) } - public convenience init(wrappedValue: Value, _ stringKey: String? = nil, nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) { - self.init(wrappedValue: wrappedValue, stringKeys: stringKey.map { [$0] }, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) + public convenience init(wrappedValue initialValue: Value, _ stringKey: String? = nil, nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) { + self.init(wrappedValue: initialValue, stringKeys: stringKey.map { [$0] }, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) } - public convenience init(wrappedValue: Value, _ stringKeys: String..., nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) { - self.init(wrappedValue: wrappedValue, stringKeys: stringKeys, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) + public convenience init(wrappedValue initialValue: Value, _ stringKeys: String..., nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) { + self.init(wrappedValue: initialValue, stringKeys: stringKeys, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) } - public convenience init(wrappedValue: Value, _ codingKeys: CodingKey..., nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) { - self.init(wrappedValue: wrappedValue, stringKeys: codingKeys.map { $0.stringValue }, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) + public convenience init(wrappedValue initialValue: Value, _ codingKeys: CodingKey..., nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) { + self.init(wrappedValue: initialValue, stringKeys: codingKeys.map { $0.stringValue }, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) } } extension ExCodable: Equatable where Value: Equatable { @@ -73,13 +73,13 @@ extension ExCodable: EncodablePropertyWrapper where Value: Encodable { } fileprivate protocol DecodablePropertyWrapper { - func decode(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool) throws + func decode(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws } extension ExCodable: DecodablePropertyWrapper where Value: Decodable { - fileprivate func decode(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool) throws { + fileprivate func decode(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws { if let value = (decode != nil ? try decode!(decoder) - : try decoder.decode(stringKeys ?? [String(label)], nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`)) { + : try decoder.decode(stringKeys ?? [String(label)], nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`, typeConverter: typeConverter)) { wrappedValue = value } } @@ -123,7 +123,7 @@ public extension Decodable { var mirror: Mirror! = Mirror(reflecting: self) while mirror != nil { for child in mirror.children where child.label != nil { - try (child.value as? DecodablePropertyWrapper)?.decode(from: decoder, label: child.label!.dropFirst(), nonnull: false, throws: false) + try (child.value as? DecodablePropertyWrapper)?.decode(from: decoder, label: child.label!.dropFirst(), nonnull: false, throws: false, typeConverter: Self.self as? ExCodableDecodingTypeConverter.Type) } mirror = mirror.superclassMirror } @@ -142,17 +142,17 @@ public extension Encoder { // , abortIfNull nonnull: Bool = false, abortOnError } public extension Decoder { // , abortIfNull nonnull: Bool = false, abortOnError throws: Bool = false - subscript(stringKeys: [String]) -> T? { - return decode(stringKeys, as: T.self) + subscript(stringKeys: [String], typeConverter typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? { + return decode(stringKeys, as: T.self, typeConverter: typeConverter) } - subscript(stringKeys: String ...) -> T? { - return decode(stringKeys, as: T.self) + subscript(stringKeys: String ..., typeConverter typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? { + return decode(stringKeys, as: T.self, typeConverter: typeConverter) } - subscript(codingKeys: [K]) -> T? { - return decode(codingKeys, as: T.self) + subscript(codingKeys: [K], typeConverter typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? { + return decode(codingKeys, as: T.self, typeConverter: typeConverter) } - subscript(codingKeys: K ...) -> T? { - return decode(codingKeys, as: T.self) + subscript(codingKeys: K ..., typeConverter typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? { + return decode(codingKeys, as: T.self, typeConverter: typeConverter) } } @@ -210,54 +210,67 @@ public extension Encoder { public extension Decoder { - func decodeNonnullThrows(_ stringKeys: String ..., as type: T.Type = T.self) throws -> T { - return try decodeNonnullThrows(stringKeys, as: type) + func decodeNonnullThrows(_ stringKeys: String ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T { + return try decodeNonnullThrows(stringKeys, as: type, typeConverter: typeConverter) } - func decodeNonnullThrows(_ stringKeys: [String], as type: T.Type = T.self) throws -> T { - return try decode(stringKeys, as: type, nonnull: true, throws: true)! + func decodeNonnullThrows(_ stringKeys: [String], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T { + return try decode(stringKeys, as: type, nonnull: true, throws: true, typeConverter: typeConverter)! } - func decodeThrows(_ stringKeys: String ..., as type: T.Type = T.self) throws -> T? { - return try decodeThrows(stringKeys, as: type) + func decodeThrows(_ stringKeys: String ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + return try decodeThrows(stringKeys, as: type, typeConverter: typeConverter) } - func decodeThrows(_ stringKeys: [String], as type: T.Type = T.self) throws -> T? { - return try decode(stringKeys, as: type, nonnull: false, throws: true) + func decodeThrows(_ stringKeys: [String], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + return try decode(stringKeys, as: type, nonnull: false, throws: true, typeConverter: typeConverter) } - func decode(_ stringKeys: String ..., as type: T.Type = T.self) -> T? { - return decode(stringKeys, as: type) + func decode(_ stringKeys: String ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + return decode(stringKeys, as: type, typeConverter: typeConverter) } - func decode(_ stringKeys: [String], as type: T.Type = T.self) -> T? { - return try? decode(stringKeys, as: type, nonnull: false, throws: false) + func decode(_ stringKeys: [String], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + return try? decode(stringKeys, as: type, nonnull: false, throws: false, typeConverter: typeConverter) } - internal/* fileprivate */ func decode(_ stringKeys: [String], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false) throws -> T? { - return try decode(stringKeys.map { ExCodingKey($0) }, as: type, nonnull: nonnull, throws: `throws`) + // TODO: DEPRECATED + internal func decode(_ stringKeys: [String], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) throws -> T? { + return try decode(stringKeys.map { ExCodingKey($0) }, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) } + // fileprivate func decode(_ stringKeys: [String], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + // return try decode(stringKeys.map { ExCodingKey($0) }, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) + // } - func decodeNonnullThrows(_ codingKeys: K ..., as type: T.Type = T.self) throws -> T { - return try decodeNonnullThrows(codingKeys, as: type) + func decodeNonnullThrows(_ codingKeys: K ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T { + return try decodeNonnullThrows(codingKeys, as: type, typeConverter: typeConverter) } - func decodeNonnullThrows(_ codingKeys: [K], as type: T.Type = T.self) throws -> T { - return try decode(codingKeys, as: type, nonnull: true, throws: true)! + func decodeNonnullThrows(_ codingKeys: [K], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T { + return try decode(codingKeys, as: type, nonnull: true, throws: true, typeConverter: typeConverter)! } - func decodeThrows(_ codingKeys: K ..., as type: T.Type = T.self) throws -> T? { - return try decodeThrows(codingKeys, as: type) + func decodeThrows(_ codingKeys: K ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + return try decodeThrows(codingKeys, as: type, typeConverter: typeConverter) } - func decodeThrows(_ codingKeys: [K], as type: T.Type = T.self) throws -> T? { - return try decode(codingKeys, as: type, nonnull: false, throws: true) + func decodeThrows(_ codingKeys: [K], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + return try decode(codingKeys, as: type, nonnull: false, throws: true, typeConverter: typeConverter) } - func decode(_ codingKeys: K ..., as type: T.Type = T.self) -> T? { - return decode(codingKeys, as: type) + func decode(_ codingKeys: K ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + return decode(codingKeys, as: type, typeConverter: typeConverter) } - func decode(_ codingKeys: [K], as type: T.Type = T.self) -> T? { - return try? decode(codingKeys, as: type, nonnull: false, throws: false) + func decode(_ codingKeys: [K], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + return try? decode(codingKeys, as: type, nonnull: false, throws: false, typeConverter: typeConverter) } - internal/* fileprivate */ func decode(_ codingKeys: [K], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false) throws -> T? { + // TODO: DEPRECATED + internal func decode(_ codingKeys: [K], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) throws -> T? { do { let container = try self.container(keyedBy: K.self) - return try container.decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`) + return try container.decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) } catch { if `throws` || nonnull { throw error } } return nil } + // fileprivate func decode(_ codingKeys: [K], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + // do { + // let container = try self.container(keyedBy: K.self) + // return try container.decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) + // } + // catch { if `throws` || nonnull { throw error } } + // return nil + // } } // MARK: - ExCodingKey @@ -276,12 +289,12 @@ extension ExCodingKey: CodingKey { fileprivate extension KeyedDecodingContainer { - func decodeForAlternativeKeys(_ codingKeys: [Self.Key], as type: T.Type = T.self, nonnull: Bool, throws: Bool) throws -> T? { + func decodeForAlternativeKeys(_ codingKeys: [Self.Key], as type: T.Type = T.self, nonnull: Bool, throws: Bool, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { var firstError: Error? do { let codingKey = codingKeys.first! - if let value = try decodeForNestedKeys(codingKey, as: type, nonnull: nonnull, throws: `throws`) { + if let value = try decodeForNestedKeys(codingKey, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) { return value } } @@ -289,7 +302,7 @@ fileprivate extension KeyedDecodingContainer { let codingKeys = Array(codingKeys.dropFirst()) if !codingKeys.isEmpty, - let value = try? decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`) { + let value = try? decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) { return value } @@ -297,11 +310,11 @@ fileprivate extension KeyedDecodingContainer { return nil } - func decodeForNestedKeys(_ codingKey: Self.Key, as type: T.Type = T.self, nonnull: Bool, throws: Bool) throws -> T? { + func decodeForNestedKeys(_ codingKey: Self.Key, as type: T.Type = T.self, nonnull: Bool, throws: Bool, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { var firstError: Error? do { - if let value = try decodeForValue(codingKey, as: type, nonnull: nonnull, throws: `throws`) { + if let value = try decodeForValue(codingKey, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) { return value } } @@ -314,7 +327,7 @@ fileprivate extension KeyedDecodingContainer { if !keys.isEmpty, let container = nestedContainer(with: keys.dropLast()), let codingKey = keys.last, - let value = try? container.decodeForNestedKeys(codingKey as! Self.Key, as: type, nonnull: nonnull, throws: `throws`) { + let value = try? container.decodeForNestedKeys(codingKey as! Self.Key, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) { return value } } @@ -332,7 +345,7 @@ fileprivate extension KeyedDecodingContainer { return container } - func decodeForValue(_ codingKey: Self.Key, as type: T.Type = T.self, nonnull: Bool, throws: Bool) throws -> T? { + func decodeForValue(_ codingKey: Self.Key, as type: T.Type = T.self, nonnull: Bool, throws: Bool, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { var firstError: Error? do { @@ -344,16 +357,61 @@ fileprivate extension KeyedDecodingContainer { } catch { firstError = error } - if contains(codingKey), - let value = decodeForTypeConversion(codingKey, as: type) { - return value + if contains(codingKey) { + if let value = decodeForTypeConversion(codingKey, as: type, typeConverter: typeConverter) { + return value + } + if #available(iOS 16.0.0, *) { + + // TODO: how to fix "Type 'any Decodable' cannot conform to 'Decodable'" + // if let rawType = type as? any (Decodable&RawRepresentable).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + + if let rawType = type as? any (Decodable&RawRepresentable< Bool >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + + if let rawType = type as? any (Decodable&RawRepresentable< Int >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable< Int8 >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable< Int16>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable< Int32>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable< Int64>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + + if let rawType = type as? any (Decodable&RawRepresentable< UInt >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable< UInt8 >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable< UInt16>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable< UInt32>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable< UInt64>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + + if let rawType = type as? any (Decodable&RawRepresentable).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + if let rawType = type as? any (Decodable&RawRepresentable).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + // if let rawType = type as? any (Decodable&RawRepresentable).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + // if let rawType = type as? any (Decodable&RawRepresentable).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + + if let rawType = type as? any (Decodable&RawRepresentable).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T } + } } if firstError != nil && (`throws` || nonnull) { throw firstError! } return nil } - func decodeForTypeConversion(_ codingKey: Self.Key, as type: T.Type = T.self) -> T? { + // TODO: how to fix "Type 'any Decodable' cannot conform to 'Decodable'" + // func decodeForRawRepresentable>(_ codingKey: Self.Key, as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + // if let rawValue = decodeForTypeConversion(codingKey, as: T.RawValue.self, typeConverter: typeConverter) { + // return type.init(rawValue: rawValue) + // } + // return nil + // } + + func decodeForRawRepresentable(_ codingKey: Self.Key, as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? where T: RawRepresentable, T.RawValue: Decodable { + if let rawValue = decodeForTypeConversion(codingKey, as: T.RawValue.self, typeConverter: typeConverter) { + return type.init(rawValue: rawValue) + } + return nil + } + + func decodeForTypeConversion(_ codingKey: Self.Key, as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { if type is Bool.Type { if let int = try? decodeIfPresent(Int.self, forKey: codingKey) { @@ -397,6 +455,7 @@ fileprivate extension KeyedDecodingContainer { else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return Int64(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Int64(string) { return value as? T } } + else if type is UInt.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt(bool ? 1 : 0) as? T } else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt(string) { return value as? T } @@ -426,20 +485,43 @@ fileprivate extension KeyedDecodingContainer { if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float(int64) as? T } // include all Int types else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float(string) { return value as? T } } - else if type is String.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return String(describing: bool) as? T } else if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return String(describing: int64) as? T } // include all Int types else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return String(describing: double) as? T } // include Float } - for converter in _decodingTypeConverters { - if let value = try? converter.decode(self, codingKey: codingKey, as: type) { - return value + if #available(iOS 14.0, *) { + if type is Float16.Type { + if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float16(int64) as? T } // include all Int types + else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float16(string) { return value as? T } + } + else if type is Float32.Type { + if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float32(int64) as? T } // include all Int types + else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float32(string) { return value as? T } } + else if type is Float64.Type { + if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float64(int64) as? T } // include all Int types + else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float64(string) { return value as? T } + } + // else if type is Float80.Type { + // if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float80(int64) as? T } // include all Int types + // else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float80(string) { return value as? T } + // } + // else if type is Float96.Type { + // if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float96(int64) as? T } // include all Int types + // else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float96(string) { return value as? T } + // } } - if let customConverter = self as? ExCodableDecodingTypeConverter, - let value = try? customConverter.decode(self, codingKey: codingKey, as: type) { + + // specific converter for type `T`, via `extension T: ExCodableDecodingTypeConverter` + if let typeConverter, + let value = try? typeConverter.decode(self, codingKey: codingKey, as: type) { + return value + } + // global converter for all types, via `extension KeyedDecodingContainer: ExCodableDecodingTypeConverter` + if let selfConverter = Self.self as? ExCodableDecodingTypeConverter.Type, + let value = try? selfConverter.decode(self, codingKey: codingKey, as: type) { return value } @@ -448,12 +530,7 @@ fileprivate extension KeyedDecodingContainer { } public protocol ExCodableDecodingTypeConverter { - func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) throws -> T? -} - -fileprivate var _decodingTypeConverters: [ExCodableDecodingTypeConverter] = [] -public func register(_ decodingTypeConverter: ExCodableDecodingTypeConverter) { - _decodingTypeConverters.append(decodingTypeConverter) + static func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) throws -> T? } // MARK: - Encodable & Decodable - external diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index ebfe97f..d6e8363 100644 --- a/Tests/ExCodableTests/ExCodableTests.swift +++ b/Tests/ExCodableTests/ExCodableTests.swift @@ -67,6 +67,18 @@ struct TestStruct: Equatable { } extension TestStruct: ExAutoCodable {} +// MARK: struct with enum + +enum TestEnum: Int, Codable { + case zero = 0, one = 1 +} + +struct TestStructWithEnum: Equatable { + @ExCodable("enum") + private(set) var `enum`: TestEnum = .zero +} +extension TestStructWithEnum: ExAutoCodable {} + // MARK: alternative-keys & alternative-keyMapping struct TestAlternativeKeys: Equatable { @@ -95,11 +107,11 @@ struct TestCustomEncodeDecode: Equatable { var int: Int = 0 @ExCodable(encode: { encoder, value in encoder["nested.nested.string"] = value }, - decode: { decoder in return decoder["nested.nested.string"] }) + decode: { decoder in return decoder["nested.nested.string"/*, typeConverter: Self.self*/] }) var string: String? = nil @ExCodable(encode: { encoder, value in encoder[Keys.bool] = value }, - decode: { decoder in return decoder[Keys.bool] }) + decode: { decoder in return decoder[Keys.bool/*, typeConverter: Self.self*/] }) var bool: Bool = false } @@ -125,7 +137,7 @@ extension TestCustomEncodeDecode: Codable { init(from decoder: Decoder) throws { try decode(from: decoder, nonnull: false, throws: false) - string = decoder["nested.nested.string"] + string = decoder["nested.nested.string"/*, typeConverter: Self.self*/] if string == nil || string == Self.dddd { string = string(for: int) } @@ -151,17 +163,17 @@ extension TestSubscript: Encodable, Decodable { init(from decoder: Decoder) throws { // - seealso: - // string = decoder.decode(<#T##codingKeys: CodingKey...##CodingKey#>) - // string = try decoder.decodeThrows(<#T##codingKeys: CodingKey...##CodingKey#>) - // string = try decoder.decodeNonnullThrows(<#T##codingKeys: CodingKey...##CodingKey#>) - int = decoder[Keys.int] ?? 0 - string = decoder[Keys.string] ?? "" + // string = decoder.decode(Keys.string, as: String.self, typeConverter: Self.self)! + // string = try decoder.decodeThrows(Keys.string, as: String.self, typeConverter: Self.self)! + // string = try decoder.decodeNonnullThrows(Keys.string, as: String.self, typeConverter: Self.self) + int = decoder[Keys.int/*, typeConverter: Self.self*/] ?? 0 + string = decoder[Keys.string/*, typeConverter: Self.self*/] ?? "" } func encode(to encoder: Encoder) throws { // - seealso: - // encoder.encode(<#T##value: Encodable?##Encodable?#>, for: <#T##CodingKey#>) - // try encoder.encodeThrows(<#T##value: Encodable?##Encodable?#>, for: <#T##CodingKey#>) - // try encoder.encodeNonnullThrows(<#T##value: Encodable##Encodable#>, for: <#T##CodingKey#>) + // encoder.encode(string, for: Keys.string) + // try encoder.encodeThrows(string, for: Keys.string) + // try encoder.encodeNonnullThrows(string, for: Keys.string) encoder[Keys.int] = int encoder[Keys.string] = string } @@ -190,20 +202,20 @@ extension TestTypeConversions: Encodable, Decodable { } init(from decoder: Decoder) throws { - boolFromInt = decoder[Keys.boolFromInt] - boolFromString = decoder[Keys.boolFromString] - intFromBool = decoder[Keys.intFromBool] - intFromDouble = decoder[Keys.intFromDouble] - intFromString = decoder[Keys.intFromString] - uIntFromBool = decoder[Keys.uIntFromBool] - uIntFromString = decoder[Keys.uIntFromString] - doubleFromInt64 = decoder[Keys.doubleFromInt64] - doubleFromString = decoder[Keys.doubleFromString] - floatFromInt64 = decoder[Keys.floatFromInt64] - floatFromString = decoder[Keys.floatFromString] - stringFromBool = decoder[Keys.stringFromBool] - stringFromInt64 = decoder[Keys.stringFromInt64] - stringFromDouble = decoder[Keys.stringFromDouble] + boolFromInt = decoder[Keys.boolFromInt/*, typeConverter: Self.self*/] + boolFromString = decoder[Keys.boolFromString/*, typeConverter: Self.self*/] + intFromBool = decoder[Keys.intFromBool/*, typeConverter: Self.self*/] + intFromDouble = decoder[Keys.intFromDouble/*, typeConverter: Self.self*/] + intFromString = decoder[Keys.intFromString/*, typeConverter: Self.self*/] + uIntFromBool = decoder[Keys.uIntFromBool/*, typeConverter: Self.self*/] + uIntFromString = decoder[Keys.uIntFromString/*, typeConverter: Self.self*/] + doubleFromInt64 = decoder[Keys.doubleFromInt64/*, typeConverter: Self.self*/] + doubleFromString = decoder[Keys.doubleFromString/*, typeConverter: Self.self*/] + floatFromInt64 = decoder[Keys.floatFromInt64/*, typeConverter: Self.self*/] + floatFromString = decoder[Keys.floatFromString/*, typeConverter: Self.self*/] + stringFromBool = decoder[Keys.stringFromBool/*, typeConverter: Self.self*/] + stringFromInt64 = decoder[Keys.stringFromInt64/*, typeConverter: Self.self*/] + stringFromDouble = decoder[Keys.stringFromDouble/*, typeConverter: Self.self*/] } func encode(to encoder: Encoder) throws { @@ -246,8 +258,23 @@ extension TestTypeConversions: Encodable, Decodable { // } // } -struct FloatToBoolDecodingTypeConverter: ExCodableDecodingTypeConverter { - public func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { +struct TestCustomTypeConverter: Equatable { + @ExCodable("enum") + private(set) var `enum`: TestEnum = .zero + @ExCodable("doubleFromBool") + var doubleFromBool: Double? = nil +} +extension TestCustomTypeConverter: ExAutoCodable {} + +extension TestCustomTypeConverter: ExCodableDecodingTypeConverter { + static public func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { + // String -> TestEnum + if type is TestEnum.Type || type is TestEnum?.Type { + if let string = try? container.decodeIfPresent(String.self, forKey: codingKey), + let int = Int(string) { + return TestEnum(rawValue: int) as? T + } + } // Bool -> Double if type is Double.Type || type is Double?.Type { if let bool = try? container.decodeIfPresent(Bool.self, forKey: codingKey) { @@ -265,12 +292,6 @@ struct FloatToBoolDecodingTypeConverter: ExCodableDecodingTypeConverter { } } -struct TestCustomTypeConverter: Equatable { - @ExCodable("doubleFromBool") - var doubleFromBool: Double? = nil -} -extension TestCustomTypeConverter: ExAutoCodable {} - // MARK: class class TestClass: Codable, Equatable { @@ -376,6 +397,56 @@ final class ExCodableTests: XCTestCase { } } + func testStructWithEnum() { + let test = TestStructWithEnum(enum: .one) + if let data = try? test.encoded() as Data, + let copy1 = try? data.decoded() as TestStructWithEnum, + let copy2 = try? TestStructWithEnum.decoded(from: data) { + XCTAssertEqual(copy1, test) + XCTAssertEqual(copy2, test) + + let string = String(data: data, encoding: .utf8) + print("TestStructWithEnum: \(string ?? "")") + } + else { + XCTFail() + } + } + + func testStructWithEnumFromJSON() { + let json = Data(#"{"enum":1}"#.utf8) + if let test = try? json.decoded() as TestStructWithEnum, + let data = try? test.encoded() as Data, + let copy = try? data.decoded() as TestStructWithEnum { + XCTAssertEqual(test, TestStructWithEnum(enum: .one)) + XCTAssertEqual(copy, test) + let localJSON = try! JSONSerialization.jsonObject(with: data) as! [String: Any] + XCTAssertEqual(NSDictionary(dictionary: localJSON), [ + "enum": 1 + ]) + } + else { + XCTFail() + } + } + + func testStructWithEnumFromJSONWithString() { + let json = Data(#"{"enum":"1"}"#.utf8) + if let test = try? json.decoded() as TestStructWithEnum, + let data = try? test.encoded() as Data, + let copy = try? data.decoded() as TestStructWithEnum { + XCTAssertEqual(test, TestStructWithEnum(enum: .one)) + XCTAssertEqual(copy, test) + let localJSON = try! JSONSerialization.jsonObject(with: data) as! [String: Any] + XCTAssertEqual(NSDictionary(dictionary: localJSON), [ + "enum": 1 + ]) + } + else { + XCTFail() + } + } + func testAlternativeKeys() { let json = Data(#"{"i":403,"s":"Forbidden"}"#.utf8) if let test = try? json.decoded() as TestAlternativeKeys, @@ -528,14 +599,14 @@ final class ExCodableTests: XCTestCase { } func testCustomTypeConverter() { - register(FloatToBoolDecodingTypeConverter()) let data = Data(#""" { + "enum": "1", "doubleFromBool": true } """#.utf8) if let test = try? data.decoded() as TestCustomTypeConverter { - XCTAssertEqual(test, TestCustomTypeConverter(doubleFromBool: 1.0)) + XCTAssertEqual(test, TestCustomTypeConverter(enum: .one, doubleFromBool: 1.0)) } else { XCTFail()