diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 1cfa351..aae5ab6 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -2,16 +2,17 @@ name: Build and Test on: push: - branches: [ master ] + branches: [ master, develop ] pull_request: - branches: [ master ] + branches: [ master, develop ] workflow_dispatch: jobs: build: runs-on: macos-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 + - uses: swift-actions/setup-swift@v2 - name: Build run: swift build -v - name: Run tests diff --git a/.github/workflows/deploy_to_cocoapods.yml b/.github/workflows/deploy_to_cocoapods.yml index f241cb4..f17cbf7 100644 --- a/.github/workflows/deploy_to_cocoapods.yml +++ b/.github/workflows/deploy_to_cocoapods.yml @@ -10,7 +10,7 @@ jobs: build: runs-on: macOS-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 - name: Install Cocoapods run: gem install cocoapods - name: Deploy to Cocoapods diff --git a/ExCodable.podspec b/ExCodable.podspec index 070e872..29fae1f 100644 --- a/ExCodable.podspec +++ b/ExCodable.podspec @@ -3,25 +3,25 @@ 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.5.0" + s.version = ENV["LIB_VERSION"] || "1.0.0-rc02" s.summary = "Key-Mapping Extensions for Swift Codable" # s.description = "Key-Mapping Extensions for Swift Codable." - s.homepage = "https://github.com/iwill/ExCodable" + s.homepage = "https://github.com/ExCodable/ExCodable" # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # s.license = "MIT" - s.author = { "Mr. Ming" => "i+ExCodable@iwill.im" } + s.author = { "Míng" => "i+ExCodable@iwill.im" } s.social_media_url = "https://iwill.im/about/" # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - s.ios.deployment_target = "9.0" - s.tvos.deployment_target = "9.0" - s.osx.deployment_target = "10.10" - s.watchos.deployment_target = "2.0" - s.swift_version = "5.0" + s.ios.deployment_target = "12.0" + s.tvos.deployment_target = "12.0" + s.macos.deployment_target = "11.0" + s.watchos.deployment_target = "4.0" + s.swift_version = "5.10" # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # - s.source = { :git => "https://github.com/iwill/ExCodable.git", :tag => s.version.to_s } + s.source = { :git => "https://github.com/ExCodable/ExCodable.git", :tag => s.version.to_s } # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # s.source_files = "Sources", "Sources/**/*.{swift}" @@ -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/LICENSE b/LICENSE index f66b212..0977b98 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2021 Mr. Ming +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/Package.swift b/Package.swift index 0f9b40c..72a6216 100644 --- a/Package.swift +++ b/Package.swift @@ -1,30 +1,26 @@ -// swift-tools-version:5.3 +// swift-tools-version:5.10 import PackageDescription let package = Package( name: "ExCodable", platforms: [ - .iOS(.v9), - .tvOS(.v9), - .macOS(.v10_10), - .watchOS(.v2) + .iOS(.v12), + .tvOS(.v12), + .macOS(.v11), + .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") ], targets: [ - .target( - name: "ExCodable", - dependencies: []), - .testTarget( - name: "ExCodableTests", - dependencies: ["ExCodable"]), + .target(name: "ExCodable", dependencies: []), + .testTarget(name: "ExCodableTests", dependencies: ["ExCodable"]) ], swiftLanguageVersions: [.v5] ) diff --git a/README.md b/README.md index fdb81b7..2da0241 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,94 @@ -[![ExCodable](https://iwill.im/images/ExCodable-1920x500.png)](#readme) +[![ExCodable](https://iwill.im/images/ExCodable-1.x-1920x500.png)](#readme) -[![Swift 5.0](https://img.shields.io/badge/Swift-5.0-orange.svg)](https://swift.org/) +[![Swift 5.10](https://img.shields.io/badge/Swift-5.10-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) +
+[![Build and Test](https://github.com/ExCodable/ExCodable/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/ExCodable/ExCodable/actions/workflows/build-and-test.yml) +[![GitHub Releases (latest SemVer)](https://img.shields.io/github/v/release/ExCodable/ExCodable.svg?sort=semver)](https://github.com/ExCodable/ExCodable/releases) +[![Deploy to CocoaPods](https://github.com/ExCodable/ExCodable/actions/workflows/deploy_to_cocoapods.yml/badge.svg)](https://github.com/ExCodable/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) +
+[![LICENSE](https://img.shields.io/github/license/ExCodable/ExCodable.svg)](https://github.com/ExCodable/ExCodable/blob/master/LICENSE) +[![GitHub stars](https://badgen.net/github/stars/ExCodable/ExCodable)](https://github.com/ExCodable/ExCodable/stargazers/) [![@minglq](https://img.shields.io/twitter/url?url=https%3A%2F%2Fgithub.com%2Fiwill%2FExCodable)](https://twitter.com/minglq) -En | [中文](https://iwill.im/ExCodable/) +En | [中文](https://excodable.iwill.im/) -## Contents +## What's New in ExCodable 1.0 + +- Uses `@propertyWrapper` instead of key-mapping, the new syntax is more concise, elegant and easier to use. +- Optimized type conversions. +- Fix bugs. + +## Documentations - [Features](#features) - [Usage](#usage) - [Requirements](#requirements) - [Installation](#installation) -- [Credits](#credits) -- [License](#license) +- [Migration](#migration) ## Features -- Extends Swift `Codable` - `Encodable & Decodable`; -- Supports Key-Mapping via `KeyPath` and Coding-Key: - - `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; - - In most cases, the `CodingKey` type is no longer necessary, because it will only be used once, `String` literals may be better. -- Supports multiple Key-Mappings for different data sources; -- Supports multiple Alternative-Keys via `Array` for decoding; -- Supports Nested-Keys via `String` with dot syntax; -- Supports customized encode/decode via subscripts; -- Supports builtin and custom Type-Conversions; -- Supports `struct`, `class` and subclass; -- Supports encode/decode with or without `IfPresent`; -- Supports abort (throws error) or continue (returns nil) encode/decode if error encountered; -- Uses JSON encoder/decoder by default, and supports PList; -- Uses Type-Inference, supports JSON `Data`, `String` and `Object`. +```swift +struct TestExCodable: ExAutoCodable { + @ExCodable private(set) + var int: Int = 0 + @ExCodable("nested.nested.string", "string", "str", "s") private(set) + var string: String? = nil +} + +``` + +- Converts between JSON and models. +- Based on and Extends Swift **`Codable`**. +- Associates JSON keys to properties via **annotations** - `@propertyWrapper`: + - `ExCodable` did not read/write memory via unsafe pointers. + - No need to encode and decode properties one by one. + - In most cases, the `CodingKey` types are no longer necessary, `String` literals are preferred. + - Currently, requires declaring properties with `var` and provide default values. +- Supports **alternative keys** for decoding. +- Supports **nested keys** via `String` with dot syntax. +- Supports builtin and custom **type conversions**, including **nested optionals** as well. +- Supports manual encoding/decoding using **subscripts**. +- Supports `return nil` or `throw error` when encoding/decoding failed. +- Supports `struct`, `enum`, `class` and subclasses. +- Supports JSON `Data`, `String`, `Array` and `Dictionary`. +- Supports **type inference**. +- Uses JSON encoder/decoder by default, supports PList and custom encoder/decoder. +- Super lightweight. + +TODO: + +- [ ] Supports `let`. +- [ ] Supports `var` without default values. +- [ ] Use Macros instead of protocol `ExAutoCodable`. ## Usage -### 0. `Codable`: + + +### 1. ExCodable + +`ExCodable` requires declaring properties with `var` and provide default values. + +```swift +struct TestStruct: ExAutoCodable { + @ExCodable private(set) + var int: Int = 0 + @ExCodable("string") private(set) + var string: String? = nil } ``` -### 1. Key-Mapping for `struct`: - -With `ExCodable`, it needs to to declare properties with `var` and provide default values. +### 2. Alternative Keys ```swift -struct TestStruct: Equatable { - private(set) var int: Int = 0 - private(set) var string: String? - var bool: Bool! +struct TestAlternativeKeys: ExAutoCodable { + @ExCodable("string", "str", "s") private(set) + var string: String! = nil } ``` +### 3. Nested Keys + ```swift -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) - // } +struct TestNestedKeys: ExAutoCodable { + @ExCodable("nested.nested.string") private(set) + var string: String! = nil } ``` -### 2. Alternative-Keys: +### 4. `enum` ```swift -static let keyMapping: [KeyMap] = [ - KeyMap(\.int, to: "int", "i"), - KeyMap(\.string, to: "string", "str", "s") -] +enum TestEnum: Int, Codable { + case zero = 0, one = 1 +} + +struct TestStructWithEnum: ExAutoCodable { + @ExCodable("enum") private(set) + var `enum` = TestEnum.zero +} ``` -### 3. Nested-Keys: +### 5. Custom Encoding/Decoding ```swift -static let keyMapping: [KeyMap] = [ - KeyMap(\.int, to: "int"), - KeyMap(\.string, to: "nested.string") -] +struct TestManualEncodeDecode: ExAutoCodable { + @ExCodable(encode: { encoder, value in + encoder["int"] = value <= 0 ? 0 : value + }, decode: { decoder in + if let int: Int = decoder["int"], int > 0 { + return int + } + return 0 + }) private(set) + var int: Int = 0 +} ``` -### 4. Custom encode/decode: +### 6. Type Conversions + +ExCodable builtin type conversions: + +- boolean: + - `Bool` + - `Int`, `Int8`, `Int16`, `Int32`, `Int64` + - `UInt`, `UInt8`, `UInt16`, `UInt32`, `UInt64` + - `String` +- integer: + - `Bool` + - `Int`, `Int8`, `Int16`, `Int32`, `Int64` + - `UInt`, `UInt8`, `UInt16`, `UInt32`, `UInt64` + - `Double`, `Float` + - `String` +- float: + - `Int`, `Int8`, `Int16`, `Int32`, `Int64` + - `UInt`, `UInt8`, `UInt16`, `UInt32`, `UInt64` + - `Double`, `Float` + - `String` +- string: + - `Bool` + - `Int`, `Int8`, `Int16`, `Int32`, `Int64` + - `UInt`, `UInt8`, `UInt16`, `UInt32`, `UInt64` + - `Double`, `Float` + - `String` + +Custom type conversions for specific properties: ```swift -struct TestCustomEncodeDecode: Equatable { +struct TestCustomEncodeDecode: ExAutoCodable { + @ExCodable(decode: { decoder in + if let string: String = decoder["string"] { + return string.count + } + return 0 + }) private(set) var int: Int = 0 - var string: String? } ``` +Custom type conversions for specific model: + ```swift -extension TestCustomEncodeDecode: ExCodable { +struct TestCustomTypeConverter: ExAutoCodable { + @ExCodable private(set) + var doubleFromBool: Double? = nil + @ExCodable private(set) + var floatFromBool: Double? = nil +} + +extension TestCustomTypeConverter: ExCodableDecodingTypeConverter { - private enum Keys: CodingKey { - case int, string - } - private static let dddd = "dddd" - private func string(for int: Int) -> String { - switch int { - case 100: return "Continue" - case 200: return "OK" - case 304: return "Not Modified" - case 403: return "Forbidden" - case 404: return "Not Found" - case 418: return "I'm a teapot" - case 500: return "Internal Server Error" - case 200..<400: return "success" - default: return "failure" + public static func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { + + // for nested optionals, e.g. `var int: Int??? = nil` + let wrappedType = T?.wrappedType + + // decode Double from Bool + if type is Double.Type || wrappedType is Double.Type { + if let bool = try? container.decodeIfPresent(Bool.self, forKey: codingKey) { + return (bool ? 1.0 : 0.0) as? T + } } + // decode Float from Bool + else if type is Float.Type || wrappedType is Float.Type { + if let bool = try? container.decodeIfPresent(Bool.self, forKey: codingKey) { + return (bool ? 1.0 : 0.0) as? T + } + } + + return nil } +} + +``` + +Custom type conversions for global: + +```swift +struct TestCustomGlobalTypeConverter: ExAutoCodable, Equatable { + @ExCodable("boolFromDouble") private(set) + var boolFromDouble: Bool? = nil +} + +extension ExCodableGlobalDecodingTypeConverter: ExCodableDecodingTypeConverter { - static let keyMapping: [KeyMap] = [ - KeyMap(\.int, to: Keys.int), - ] - - init(from decoder: Decoder) throws { - try decode(from: decoder, with: Self.keyMapping) - string = decoder[Keys.string] - if string == nil || string == Self.dddd { - string = string(for: int) + public static func decode(_ container: KeyedDecodingContainer<_K>, codingKey: _K, as type: T.Type) -> T? { + + // for nested optionals, e.g. `var int: Int??? = nil` + let wrappedType = T?.wrappedType + + // decode Bool from Double + if type is Bool.Type || wrappedType is Bool.Type { + if let double = try? container.decodeIfPresent(Double.self, forKey: codingKey) { + return (double != 0) as? T + } } - } - func encode(to encoder: Encoder) throws { - try encode(to: encoder, with: Self.keyMapping) - encoder[Keys.string] = Self.dddd + + return nil } } ``` -### 5. Encode/decode constant properties with subscripts: +### 7. Manual Encoding/Decoding using Subscripts -Using `let` to declare properties without default values. +A type without `ExCodable`: ```swift -struct TestSubscript: Equatable { +struct TestManualEncodingDecoding { let int: Int let string: String } ``` +Manual encoding/decoding using subscripts: + ```swift -extension TestSubscript: Encodable, Decodable { +extension TestManualEncodingDecoding: Codable { enum Keys: CodingKey { case int, string } 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] ?? "" } 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[Keys.int] = int encoder[Keys.string] = string } @@ -256,165 +348,157 @@ extension TestSubscript: Encodable, Decodable { ``` -### 6. Custom Type-Conversions: +### 8. `return nil` or `throw error` - UNSTABLE -Declare struct `FloatToBoolDecodingTypeConverter` with protocol `ExCodableDecodingTypeConverter` and implement its method, decode values in alternative types and convert to target type: +While encoding/decoding, ExCodable ignores the `keyNotFound`, `valueNotFound`, `invalidValue` and `typeMismatch` errors and `return nil` by default, only throws JSON errors. -```swift -struct FloatToBoolDecodingTypeConverter: ExCodableDecodingTypeConverter { - public 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 - } -} - -``` +ExCodable also supports throw errors: -Register `FloatToBoolDecodingTypeConverter` with an instance: +- Use `nonnull: true` to throw `EncodingError.invalidValue`, `DecodingError.keyNotFound`, `DecodingError.valueNotFound`. +- Use `throws: true` to throw `DecodingError.typeMismatch`. ```swift -register(FloatToBoolDecodingTypeConverter()) -``` +struct TestNonnullAndThrows: ExAutoCodable { + @ExCodable(nonnull: true, throws: true) private(set) + var int: Int! = 0 +} -### 7. Key-Mapping for `class`: +``` -Cannot adopt `ExCodable` in extension of classes. +### 9. `class` and Subclasses ```swift -class TestClass: ExCodable, Equatable { - +class TestClass: ExAutoCodable { + @ExCodable private(set) var int: Int = 0 + @ExCodable private(set) var string: String? = nil + required init() {} 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) - } - - static func == (lhs: TestClass, rhs: TestClass) -> Bool { - return lhs.int == rhs.int && lhs.string == rhs.string - } } ``` -### 8. Key-Mapping for subclass: - -Requires declaring another static Key-Mapping for subclass. - ```swift class TestSubclass: TestClass { + @ExCodable private(set) var bool: Bool = false + required init() { super.init() } 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 { - return lhs.int == rhs.int - && lhs.string == rhs.string - && lhs.bool == rhs.bool - } } ``` -### 9. Encode/decode with Type-Inference: +### 10. Type Inference ```swift -let test = TestStruct(int: 304, string: "Not Modified") -let data = try? test.encoded() as Data? -let copy1 = try? data?.decoded() as TestStruct? -let copy2 = data.map { try? TestStruct.decoded(from: $0) } -XCTAssertEqual(copy1, test) -XCTAssertEqual(copy2, test) +struct TestStruct: ExAutoCodable, Equatable { + @ExCodable private(set) + var int: Int = 0 + @ExCodable private(set) + var string: String? = nil +} + +let json = Data(#"{"int":200,"string":"OK"}"#.utf8) +let model = try? TestStruct.decoded(from: json) + +let dict = try? model.encoded() as [String: Any] +let copy = try? dict.decoded() as TestStruct ``` +> See the tests for more examples. + ## Requirements -- iOS 8.0+ | tvOS 9.0+ | macOS X 10.10+ | watchOS 2.0+ -- Xcode 12.0+ -- Swift 5.0+ +- iOS 12.0+ | tvOS 12.0+ | macOS 11.0+ | watchOS 4.0+ +- Xcode 15.4+ +- Swift 5.10+ ## Installation -- [Swift Package Manager](https://swift.org/package-manager/): +Swift Package Manager: ```swift -.package(url: "https://github.com/iwill/ExCodable", from: "0.5.0") +.package(url: "https://github.com/ExCodable/ExCodable", from: "1.0.0") ``` -- [CocoaPods](http://cocoapods.org): +CocoaPods: ```ruby -pod 'ExCodable', '~> 0.5.0' +pod 'ExCodable', '~> 1.0.0' ``` -- Code Snippets: +## Migration + +### 0.x to 1.x + +When you update to ExCodable 1.0. -> Title: ExCodable -> Summary: Adopte to ExCodable protocol -> Language: Swift -> Platform: All -> Completion: ExCodable -> Availability: Top Level +Step 1: Update your code to use the old API - **DEPRECATED** but quick. + +- Replace protocol `ExCodable` with `ExCodableDEPRECATED`. +- Add `static` to func `decodeForTypeConversion(_:codingKey:as:)` of protocol `KeyedDecodingContainerCustomTypeConversion`. ```swift -<#extension/struct/class#> <#Type#>: ExCodable { - static let <#keyMapping#>: [KeyMap<<#SelfType#>>] = [ - KeyMap(\.<#property#>, to: <#"key"#>), - <#...#> +struct TestExCodable { + private(set) var int: Int = 0 + private(set) var string: String? +} + +extension TestExCodable: ExCodableDEPRECATED { + static let keyMapping: [KeyMap] = [ + KeyMap(\.int, to: "int"), + KeyMap(\.string, to: "nested.nested.string", "string", "str", "s") ] init(from decoder: Decoder) throws { - try decode<#Reference#>(from: decoder, with: Self.<#keyMapping#>) - } - func encode(to encoder: Encoder) throws { - try encode(to: encoder, with: Self.<#keyMapping#>) + try decode(from: decoder, with: Self.keyMapping) } } ``` -## Credits +Step 2: Upgrade your models to the new API one by one - SUGGESTED: + +- Replace `protocol` `ExCodable` with `ExAutoCodable`. +- Remove initializer `init(from decoder: Decoder) throws`. +- Remove `static` properties `keyMapping`. +- Use `@ExCodable("", "", ...)`. +- See [Usage](#usage) for more details. + +```swift +struct TestExCodable: ExAutoCodable { + @ExCodable private(set) + var int: Int = 0 + @ExCodable("nested.nested.string", "string", "str", "s") private(set) + var string: String? +} + +``` + +## Stars + + + Star Chart + + +Hope ExCodable will help you! [Make a star](https://github.com/ExCodable/ExCodable/#repository-container-header) ⭐️ 🤩 + +## Thanks to - John Sundell ([@JohnSundell](https://github.com/JohnSundell)) and the ideas from his [Codextended](https://github.com/JohnSundell/Codextended) - ibireme ([@ibireme](https://github.com/ibireme)) and the features from his [YYModel](https://github.com/ibireme/YYModel) -- Mr. Ming ([@iwill](https://github.com/iwill)) | i+ExCodable@iwill.im + +## About Me + +- Míng ([@iwill](https://github.com/iwill)) | i+ExCodable@iwill.im ## License diff --git a/Sources/ExCodable/ExCodable+DEPRECATED.swift b/Sources/ExCodable/ExCodable+DEPRECATED.swift new file mode 100644 index 0000000..daf5b30 --- /dev/null +++ b/Sources/ExCodable/ExCodable+DEPRECATED.swift @@ -0,0 +1,163 @@ +// +// ExCodable+DEPRECATED.swift +// ExCodable +// +// Created by Míng on 2021-07-01. +// Copyright (c) 2021 Míng . Released under the MIT license. +// + +import Foundation + +// TODO: REMOVE + +/// Migration ExCodable from 0.x to 1.x: +/// +/// DEPRECATED: +/// +/// - Replace `ExCodable` with `ExCodableDEPRECATED`. +/// +/// SUGGESTED: +/// +/// - Replace `ExCodable` with `ExAutoCodable`. +/// - Remove `static` properties `keyMapping`. +/// - Remove initializer `init(from decoder: Decoder) throws`. +/// - Use `@ExCodable("", "")`. +/// + +// MARK: adaptor + +@available(*, deprecated) +fileprivate extension Encoder { + func _encode(_ value: T?, for stringKey: String, nonnull: Bool = false, throws: Bool = false) throws { + try encode(value, for: stringKey, nonnull: nonnull, throws: `throws`) + } + func _encode(_ value: T?, for codingKey: K, nonnull: Bool = false, throws: Bool = false) throws { + try encode(value, for: codingKey, nonnull: nonnull, throws: `throws`) + } +} + +@available(*, deprecated) +fileprivate extension Decoder { + func _decode(_ stringKeys: [String], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, converter: (any ExCodableDecodingTypeConverter.Type)? = nil) throws -> T? { + return try decode(stringKeys, as: type, nonnull: nonnull, throws: `throws`, converter: converter) + } + func _decode(_ codingKeys: [K], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, converter: (any ExCodableDecodingTypeConverter.Type)? = nil) throws -> T? { + try decode(codingKeys, as: type, nonnull: nonnull, throws: `throws`, converter: converter) + } +} + +// MARK: - keyMapping + +@available(*, deprecated, message: "Use property wrapper `@ExCodable` instead.") +public protocol ExCodableDEPRECATED: Codable { + associatedtype Root = Self where Root: ExCodableDEPRECATED + static var keyMapping: [KeyMap] { get } +} + +@available(*, deprecated) +public extension ExCodableDEPRECATED where Root == Self { + // default implementation of ExCodableDEPRECATED + 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 ExCodableDEPRECATED { + 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 property wrapper `@ExCodable` 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 ExCodableDEPRECATED { + @available(*, deprecated) + func encode(with keyMapping: [KeyMap], using encoder: Encoder) { + try? encode(to: encoder, with: keyMapping) + } + @available(*, deprecated) + mutating func decode(with keyMapping: [KeyMap], using decoder: Decoder) { + try? decode(from: decoder, with: keyMapping) + } + @available(*, deprecated) + func decodeReference(with keyMapping: [KeyMap], using decoder: Decoder) { + try? decodeReference(from: decoder, with: keyMapping) + } +} + +@available(*, deprecated) +public protocol KeyedDecodingContainerCustomTypeConversion: ExCodableDecodingTypeConverter { + static func decodeForTypeConversion(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? +} +@available(*, deprecated) +public extension KeyedDecodingContainerCustomTypeConversion { + static func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { + return decodeForTypeConversion(container, codingKey: codingKey, as: type) + } +} diff --git a/Sources/ExCodable/ExCodable.swift b/Sources/ExCodable/ExCodable.swift index 9e873eb..ad51145 100644 --- a/Sources/ExCodable/ExCodable.swift +++ b/Sources/ExCodable/ExCodable.swift @@ -2,100 +2,179 @@ // ExCodable.swift // ExCodable // -// Created by Mr. Ming on 2021-02-10. -// Copyright (c) 2021 Mr. Ming . Released under the MIT license. +// Created by Míng on 2021-02-10. +// Copyright (c) 2021 Míng . Released under the MIT license. // import Foundation -/** - * # ExCodable - * - * A protocol extends `Encodable` & `Decodable` with `keyMapping` - * <#swift#> <#codable#> <#json#> <#model#> <#type-inference#> - * <#key-mapping#> <#keypath#> <#codingkey#> <#subscript#> - * <#alternative-keys#> <#nested-keys#> <#type-conversion#> - * - * - seealso: [Usage](https://github.com/iwill/ExCodable#usage) from GitGub - * - seealso: `ExCodableTests.swift` form the source code - */ -public protocol ExCodable: Codable { - associatedtype Root = Self where Root: ExCodable - static var keyMapping: [KeyMap] { get } -} +/// # ExCodable +/// +/// <#swift#> <#codable#> <#json#> <#model#> <#type-inference#> +/// <#key-mapping#> <#property-wrapper#> <#coding-key#> <#subscript#> +/// <#alternative-keys#> <#nested-keys#> <#type-conversions#> +/// +/// - `ExCodable`: A `@propertyWrapper` associates JSON keys to properties. +/// - `ExAutoEncodable` & `ExAutoDecodable`: Protocols with default implementation for Encodable & Decodable. +/// - `ExAutoCodable`: A typealias for `ExAutoEncodable & ExAutoDecodable`. +/// - `Encodable` & `Decodable` extensions for encoding/decoding from internal/external. +/// - `Encoder` & `Encoder` extensions for encoding/decoding properties one by one. +/// - Supports alternative keys, nested keys, type conversions, nested optionals and default values. +/// +/// - seealso: [Usage](https://github.com/ExCodable/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. -public extension ExCodable { - 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`) } +@propertyWrapper +public final class ExCodable { + + public var wrappedValue: Value + + fileprivate let stringKeys: [String]? + fileprivate let nonnull, `throws`: Bool? + fileprivate let encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)?, + decode: ((_ decoder: Decoder) throws -> Value?)? + private let decodeRawRepresentable: ((_ decoder: Decoder, _ stringKeys: [String], _ nonnull: Bool, _ throws: Bool, _ converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> Value?)? + + 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?)?, decodeRawRepresentable: ((_ decoder: Decoder, _ stringKeys: [String], _ nonnull: Bool, _ throws: Bool, _ converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> Value?)? = nil) { + (self.wrappedValue, self.stringKeys, self.nonnull, self.throws, self.encode, self.decode, self.decodeRawRepresentable) + = (initialValue, stringKeys, nonnull, `throws`, encode, decode, decodeRawRepresentable) } - 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`) } + 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) } - 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 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 extension ExCodable where Root == Self { - func encode(to encoder: Encoder) throws { - try encode(to: encoder, with: Self.keyMapping) + 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) } } -// MARK: - +extension ExCodable where Value: RawRepresentable, Value.RawValue: Decodable { + private convenience 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?)?) where Value: RawRepresentable, Value.RawValue: Decodable { + if let decode { + self.init(wrappedValue: initialValue, stringKeys: stringKeys, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode, decodeRawRepresentable: nil) + } + else { + self.init(wrappedValue: initialValue, stringKeys: stringKeys, nonnull: nonnull, throws: `throws`, encode: encode, decode: nil, decodeRawRepresentable: { decoder, stringKeys, nonnull, `throws`, converter throws in + guard let rawValue = try decoder.decode(stringKeys, as: Value.RawValue.self, nonnull: nonnull, throws: `throws`, converter: converter), + let value = Value(rawValue: rawValue) else { return nil } + return value + }) + } + } + 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) where Value: RawRepresentable, Value.RawValue: Decodable { + self.init(wrappedValue: initialValue, stringKeys: stringKey.map { [$0] }, 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) where Value: RawRepresentable, Value.RawValue: Decodable { + self.init(wrappedValue: initialValue, stringKeys: stringKeys, 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) where Value: RawRepresentable, Value.RawValue: Decodable { + self.init(wrappedValue: initialValue, stringKeys: codingKeys.map { $0.stringValue }, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode) + } +} -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) +extension ExCodable: Equatable where Value: Equatable { + public static func == (lhs: ExCodable, rhs: ExCodable) -> Bool { + return lhs.wrappedValue == rhs.wrappedValue } } +extension ExCodable: CustomStringConvertible { // CustomDebugStringConvertible + public var description: String { String(describing: wrappedValue) } + // public var debugDescription: String { "\(type(of: self))(\(wrappedValue))" } +} -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 +fileprivate protocol ExCodablePropertyWrapper { + func encode(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws + func decode(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool, converter: (any ExCodableDecodingTypeConverter.Type)?) throws +} +extension ExCodable: ExCodablePropertyWrapper { + fileprivate func encode(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws { + let deepWrapped = if let optional = wrappedValue as? OptionalProtocol { + optional.wrapped + } + else { + wrappedValue + } + // !!!: NOT `if let deepWrapped, self.nonnull ?? nonnull` + if deepWrapped != nil || self.nonnull ?? nonnull { + if let encode { + try encode(encoder, wrappedValue) } - }, 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 + else { + try encoder.encode(wrappedValue, for: stringKeys?.first ?? String(label), nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`) } - }, 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 + } + } + fileprivate func decode(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool, converter: (any ExCodableDecodingTypeConverter.Type)?) throws { + let value = if let decode { + try decode(decoder) + } + else if let decodeRawRepresentable { + try decodeRawRepresentable(decoder, stringKeys ?? [String(label)], self.nonnull ?? nonnull, self.throws ?? `throws`, converter) + } + else { + try decoder.decode(stringKeys ?? [String(label)], as: Value.self, nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`, converter: converter) + } + if let value { + wrappedValue = value + } + } +} + +// 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 + +// TODO: internal -> fileprivate +internal 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? ExCodablePropertyWrapper)?.encode(to: encoder, label: child.label!.dropFirst(), nonnull: false, throws: false) } - }) - } - 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 + mirror = mirror.superclassMirror + } + } +} + +// TODO: internal -> fileprivate +internal extension Decodable { + func decode(from decoder: Decoder, nonnull: Bool, throws: Bool) throws { + var mirror: Mirror! = Mirror(reflecting: self) + while mirror != nil { + let converter = mirror.subjectType as? ExCodableDecodingTypeConverter.Type + for child in mirror.children where child.label != nil { + try (child.value as? ExCodablePropertyWrapper)?.decode(from: decoder, label: child.label!.dropFirst(), nonnull: false, throws: false, converter: converter) } - }) + mirror = mirror.superclassMirror + } } } -// MARK: - subscript +// MARK: - Encoder & Decoder -public extension Encoder { // , abortIfNull nonnull: Bool = false, abortOnError throws: Bool = false +public extension Encoder { // , nonnull nonnull: Bool = false, throws throws: Bool = false subscript(stringKey: String) -> T? { get { return nil } nonmutating set { encode(newValue, for: stringKey) } } @@ -104,23 +183,21 @@ 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) +public extension Decoder { // , nonnull nonnull: Bool = false, throws throws: Bool = false + subscript(stringKeys: [String], converter converter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? { + return decode(stringKeys, as: T.self, converter: converter) } - subscript(stringKeys: String ...) -> T? { - return decode(stringKeys, as: T.self) + subscript(stringKeys: String ..., converter converter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? { + return decode(stringKeys, as: T.self, converter: converter) } - subscript(codingKeys: [K]) -> T? { - return decode(codingKeys, as: T.self) + subscript(codingKeys: [K], converter converter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? { + return decode(codingKeys, as: T.self, converter: converter) } - subscript(codingKeys: K ...) -> T? { - return decode(codingKeys, as: T.self) + subscript(codingKeys: K ..., converter converter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? { + return decode(codingKeys, as: T.self, converter: converter) } } -// MARK: - - public extension Encoder { func encodeNonnullThrows(_ value: T, for stringKey: String) throws { @@ -132,7 +209,9 @@ 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 { + + // TODO: internal -> fileprivate + internal 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 { @@ -147,11 +226,19 @@ public extension Encoder { } let codingKey = keys.last! - do { - if nonnull { try container.encode(value, forKey: codingKey) } - else { try container.encodeIfPresent(value, forKey: codingKey) } + if nonnull { + if value.wrapped == nil { + let desc = "Expected to encode nonnull for \(T?.wrappedType) but found null value instead." + throw EncodingError.invalidValue(value as Any, .init(codingPath: [ExCodingKey(stringKey)], debugDescription: desc)) + } + try container.encode(value, forKey: codingKey) + } + else if `throws` { + try container.encodeIfPresent(value, forKey: codingKey) + } + else { + try? container.encodeIfPresent(value, forKey: codingKey) } - catch { if `throws` || nonnull { throw error } } } func encodeNonnullThrows(_ value: T, for codingKey: K) throws { @@ -163,161 +250,195 @@ 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 { + + // TODO: internal -> fileprivate + internal 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) } - else { try container.encodeIfPresent(value, forKey: codingKey) } + if nonnull { + if value.wrapped == nil { + let desc = "Expected to encode nonnull for \(T?.wrappedType) but found null value instead." + throw EncodingError.invalidValue(value as Any, .init(codingPath: [codingKey], debugDescription: desc)) + } + try container.encode(value, forKey: codingKey) + } + else if `throws` { + try container.encodeIfPresent(value, forKey: codingKey) + } + else { + try? container.encodeIfPresent(value, forKey: codingKey) } - catch { if `throws` || nonnull { throw error } } } } 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T { + return try decodeNonnullThrows(stringKeys, as: type, converter: converter) } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T { + return try decode(stringKeys, as: type, nonnull: true, throws: true, converter: converter)! } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + return try decodeThrows(stringKeys, as: type, converter: converter) } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + return try decode(stringKeys, as: type, nonnull: false, throws: true, converter: converter) } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + return decode(stringKeys, as: type, converter: converter) } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + return try? decode(stringKeys, as: type, nonnull: false, throws: false, converter: converter) } - 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: internal -> fileprivate + internal func decode(_ stringKeys: [String], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + return try decode(stringKeys.map { ExCodingKey($0) }, as: type, nonnull: nonnull, throws: `throws`, converter: converter) } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T { + return try decodeNonnullThrows(codingKeys, as: type, converter: converter) } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T { + return try decode(codingKeys, as: type, nonnull: true, throws: true, converter: converter)! } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + return try decodeThrows(codingKeys, as: type, converter: converter) } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + return try decode(codingKeys, as: type, nonnull: false, throws: true, converter: converter) } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + return decode(codingKeys, as: type, converter: converter) } - 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, converter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + return try? decode(codingKeys, as: type, nonnull: false, throws: false, converter: converter) } - 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`) + + // TODO: internal -> fileprivate + internal func decode(_ codingKeys: [K], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + if let container = nonnull || `throws` ? try self.container(keyedBy: K.self) : try? self.container(keyedBy: K.self) { + return try container.decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`, converter: converter) } - catch { if `throws` || nonnull { throw error } } return nil } } -private struct ExCodingKey: CodingKey { - let stringValue: String, intValue: Int? - init(_ stringValue: String) { (self.stringValue, self.intValue) = (stringValue, nil) } - init(_ stringValue: Substring) { self.init(String(stringValue)) } +// MARK: - ExCodingKey + +fileprivate struct ExCodingKey { + public let stringValue: String, intValue: Int? + init(_ stringValue: S) { (self.stringValue, self.intValue) = (stringValue as? String ?? String(stringValue), nil) } +} + +extension ExCodingKey: CodingKey { init?(stringValue: String) { self.init(stringValue) } - init(_ intValue: Int) { (self.intValue, self.stringValue) = (intValue, String(intValue)) } init?(intValue: Int) { self.init(intValue) } } -// MARK: - alternative-keys + nested-keys + type-conversion +// MARK: - KeyedDecodingContainer - alternative-keys + nested-keys + type-conversions -private extension KeyedDecodingContainer { +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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + + var caughtError: Error? - 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`, converter: converter) { return value } } - catch { firstError = error } + catch { caughtError = error } - let codingKeys = Array(codingKeys.dropFirst()) - if !codingKeys.isEmpty, - let value = try? decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`) { - return value + do { + let codingKeys = Array(codingKeys.dropFirst()) + if !codingKeys.isEmpty, + let value = try decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`, converter: converter) { + return value + } } + catch { caughtError = caughtError ?? error } - if (`throws` || nonnull) && firstError != nil { throw firstError! } + if let caughtError { throw caughtError } 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { + + var caughtError: Error? - 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`, converter: converter) { return value } } - catch { firstError = error } + catch { caughtError = error } - let dot: Character = "." - if let exCodingKey = codingKey as? ExCodingKey, // Self.Key is ExCodingKey.Type - exCodingKey.intValue == nil && exCodingKey.stringValue.contains(dot) { - let keys = exCodingKey.stringValue.split(separator: dot).map { ExCodingKey($0) } - 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`) { - return value + do { + let dot: Character = "." + if let exCodingKey = codingKey as? ExCodingKey, // Self.Key is ExCodingKey.Type + exCodingKey.intValue == nil && exCodingKey.stringValue.contains(dot) { + let keys = exCodingKey.stringValue.split(separator: dot).map { ExCodingKey($0) } + 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`, converter: converter) { + return value + } } } + catch { caughtError = caughtError ?? error } - if firstError != nil && (`throws` || nonnull) { throw firstError! } + if let caughtError { throw caughtError } return nil } private func nestedContainer(with keys: [ExCodingKey]) -> Self? { var container: Self? = self for key in keys { - container = try? container?.nestedContainer(keyedBy: Self.Key, forKey: key as! Self.Key) + container = try? container?.nestedContainer(keyedBy: Self.Key.self, forKey: key as! Self.Key) if container == nil { return nil } } 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, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? { - var firstError: Error? + var caughtError: 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 nonnull { + let value = try decode(type, forKey: codingKey) + if let optional = value as? OptionalProtocol, optional.wrapped == nil { + let desc = "Expected to decode nonnull for \(type) but found null value instead." + throw DecodingError.valueNotFound(type, .init(codingPath: [codingKey], debugDescription: desc)) + } + return value + } + if let value = `throws` + ? try decodeIfPresent(type, forKey: codingKey) + : try? decodeIfPresent(type, forKey: codingKey) { return value } } - catch { firstError = error } + catch { caughtError = error } if contains(codingKey), - let value = decodeForTypeConversion(codingKey, as: type) { + let value = decodeForTypeConversion(codingKey, as: type, converter: converter) { return value } - if firstError != nil && (`throws` || nonnull) { throw firstError! } + if let caughtError { throw caughtError } return nil } - func decodeForTypeConversion(_ codingKey: Self.Key, as type: T.Type = T.self) -> T? { + func decodeForTypeConversion(_ codingKey: Self.Key, as type: T.Type = T.self, converter specificConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? { + + // for nested optionals, e.g. `var int: Int??? = nil` + let wrappedType = T?.wrappedType - if type is Bool.Type { + if type is Bool.Type || wrappedType is Bool.Type { if let int = try? decodeIfPresent(Int.self, forKey: codingKey) { return (int != 0) as? T } @@ -334,74 +455,107 @@ private extension KeyedDecodingContainer { } } - else if type is Int.Type { + else if type is Int.Type || wrappedType is Int.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return Int(bool ? 1 : 0) as? T } else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return Int(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Int(string) { return value as? T } } - else if type is Int8.Type { + else if type is Int8.Type || wrappedType is Int8.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return Int8(bool ? 1 : 0) as? T } else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return Int8(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Int8(string) { return value as? T } } - else if type is Int16.Type { + else if type is Int16.Type || wrappedType is Int16.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return Int16(bool ? 1 : 0) as? T } else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return Int16(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Int16(string) { return value as? T } } - else if type is Int32.Type { + else if type is Int32.Type || wrappedType is Int32.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return Int32(bool ? 1 : 0) as? T } else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return Int32(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Int32(string) { return value as? T } } - else if type is Int64.Type { + else if type is Int64.Type || wrappedType is Int64.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return Int64(bool ? 1 : 0) as? T } 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 { + + else if type is UInt.Type || wrappedType is UInt.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt(bool ? 1 : 0) as? T } + else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return UInt(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt(string) { return value as? T } } - else if type is UInt8.Type { + else if type is UInt8.Type || wrappedType is UInt8.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt8(bool ? 1 : 0) as? T } + else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return UInt8(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt8(string) { return value as? T } } - else if type is UInt16.Type { + else if type is UInt16.Type || wrappedType is UInt16.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt16(bool ? 1 : 0) as? T } + else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return UInt16(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt16(string) { return value as? T } } - else if type is UInt32.Type { + else if type is UInt32.Type || wrappedType is UInt32.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt32(bool ? 1 : 0) as? T } + else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return UInt32(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt32(string) { return value as? T } } - else if type is UInt64.Type { + else if type is UInt64.Type || wrappedType is UInt64.Type { if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt64(bool ? 1 : 0) as? T } + else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return UInt64(double) as? T } // include Float else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt64(string) { return value as? T } } - else if type is Double.Type { + else if type is Double.Type || wrappedType is Double.Type { if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Double(int64) as? T } // include all Int types else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Double(string) { return value as? T } } - else if type is Float.Type { + else if type is Float.Type || wrappedType is Float.Type { 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 { + else if type is String.Type || wrappedType 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 conversion in _decodingTypeConverters { - if let value = try? conversion.decode(self, codingKey: codingKey, as: type) { - return value +#if os(iOS) || os(tvOS) + if #available(iOS 14.0, tvOS 14.0, macOS 11.0, watchOS 7.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 } + // } + } +#endif + + // converter for specific type, via `extension T: ExCodableDecodingTypeConverter` + if let specificConverter, + let value = specificConverter.decode(self, codingKey: codingKey, as: type) { + return value } - if let custom = self as? ExCodableDecodingTypeConverter, - let value = try? custom.decode(self, codingKey: codingKey, as: type) { + + // global converter for all types, via `extension KeyedDecodingContainer: ExCodableDecodingTypeConverter` + if let globalConverter = ExCodableGlobalDecodingTypeConverter.self as? ExCodableDecodingTypeConverter.Type, + let value = globalConverter.decode(self, codingKey: codingKey, as: type) { return value } @@ -410,16 +564,27 @@ private extension KeyedDecodingContainer { } public protocol ExCodableDecodingTypeConverter { - func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) throws -> T? + static func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? } +public struct ExCodableGlobalDecodingTypeConverter {} -private var _decodingTypeConverters: [ExCodableDecodingTypeConverter] = [] -public func register(_ decodingTypeConverter: ExCodableDecodingTypeConverter) { - _decodingTypeConverters.append(decodingTypeConverter) +// MARK: - Encodable & Decodable - external + +// Methods defined in JSON&PList Encoder&Decoder +public protocol DataEncoder { + func encode(_ value: T) throws -> Data +} +public protocol DataDecoder { + func decode(_ type: T.Type, from data: Data) throws -> T } -// MARK: - Encodable/Decodable -// - seealso: [Codextended](https://github.com/JohnSundell/Codextended) +extension JSONEncoder: DataEncoder {} +extension JSONDecoder: DataDecoder {} + +@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 {} // Encodable.encode() -> Data? public extension Encodable { @@ -483,46 +648,32 @@ public extension String { } } -// Methods from JSON&PList Encoder&Decoder -public protocol DataEncoder { - func encode(_ value: T) throws -> Data -} -public protocol DataDecoder { - func decode(_ type: T.Type, from data: Data) throws -> T -} - -extension JSONEncoder: DataEncoder {} -extension JSONDecoder: DataDecoder {} - -#if canImport(ObjectiveC) || swift(>=5.1) -extension PropertyListEncoder: DataEncoder {} -extension PropertyListDecoder: DataDecoder {} -#endif +// MARK: - OptionalProtocol for Nested Optional -// MARK: - #### DEPRECATED #### +// - seealso: https://forums.swift.org/t/challenge-finding-base-type-of-nested-optionals/25096 -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) - } +public protocol OptionalProtocol { + static var wrappedType: Any.Type { get } + var wrapped: Any? { get } } -@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) +extension Optional: OptionalProtocol { + + public static var wrappedType: Any.Type { + if let optional = Wrapped.self as? OptionalProtocol.Type { + return optional.wrappedType + } + return Wrapped.self + } + + public var wrapped: Any? { + return switch self { + case .some(let optional as OptionalProtocol): + optional.wrapped + case .some(let wrapped): + wrapped + case .none: + nil + } } } diff --git a/Tests/ExCodableTests/ExCodableTests.swift b/Tests/ExCodableTests/ExCodableTests.swift index ce7976d..0626569 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 Míng on 2021-02-10. +// Copyright (c) 2023 Míng . Released under the MIT license. // import XCTest @@ -11,6 +11,15 @@ import XCTest // @testable import ExCodable +// MARK: ExCodable + +struct TestExCodable: ExAutoCodable, Equatable { + @ExCodable private(set) + var int: Int = 0 + @ExCodable private(set) + var string: String? = nil +} + // MARK: auto codable struct TestAutoCodable: Codable, Equatable { @@ -31,18 +40,22 @@ struct TestManualCodable: Equatable { extension TestManualCodable: Codable { enum Keys: CodingKey { - case int, i - case nested, string + case int + case nested, string, s } init(from decoder: Decoder) throws { if let container = try? decoder.container(keyedBy: Keys.self) { - if let int = (try? container.decodeIfPresent(Int.self, forKey: Keys.int)) - ?? (try? container.decodeIfPresent(Int.self, forKey: Keys.i)) { + if let int = try? container.decodeIfPresent(Int.self, forKey: Keys.int) { self.int = int } if let nestedContainer = try? container.nestedContainer(keyedBy: Keys.self, forKey: Keys.nested), - let string = try? nestedContainer.decodeIfPresent(String.self, forKey: Keys.string) { + let nestedNestedContainer = try? nestedContainer.nestedContainer(keyedBy: Keys.self, forKey: Keys.nested), + let string = try? nestedNestedContainer.decodeIfPresent(String.self, forKey: Keys.string) { + self.string = string + } + else if let string = (try? container.decodeIfPresent(String.self, forKey: Keys.string)) + ?? (try? container.decodeIfPresent(String.self, forKey: Keys.s)) { self.string = string } } @@ -52,131 +65,113 @@ extension TestManualCodable: Codable { var container = encoder.container(keyedBy: Keys.self) try? container.encodeIfPresent(int, forKey: Keys.int) var nestedContainer = container.nestedContainer(keyedBy: Keys.self, forKey: Keys.nested) - try? nestedContainer.encodeIfPresent(string, forKey: Keys.string) + var nestedNestedContainer = nestedContainer.nestedContainer(keyedBy: Keys.self, forKey: Keys.nested) + try? nestedNestedContainer.encodeIfPresent(string, forKey: Keys.string) } } -// MARK: struct +// MARK: DEPRECATED -struct TestStruct: Equatable { +struct TestExCodable_0_x: Equatable { private(set) var int: Int = 0 private(set) var string: String? - var bool: Bool! } -extension TestStruct: ExCodable { - +@available(*, deprecated) +extension TestExCodable_0_x: ExCodableDEPRECATED { static let keyMapping: [KeyMap] = [ KeyMap(\.int, to: "int"), - KeyMap(\.string, to: "string"), + 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) - // } } -// MARK: alternative-keys & alternative-keyMapping +// MARK: struct -struct TestAlternativeKeys: Equatable { +struct TestStruct: ExAutoCodable, Equatable { + @ExCodable("int") private(set) var int: Int = 0 - var string: String! + @ExCodable("string") private(set) + var string: String? = nil + var bool: Bool! } -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 - } +// MARK: struct with enum + +enum TestEnum: Int, Codable { + case zero = 0, one = 1 } -// MARK: nested-keys +struct TestStructWithEnum: ExAutoCodable, Equatable { + @ExCodable private(set) + var `enum` = TestEnum.zero +} -struct TestNestedKeys: Equatable { +// MARK: alternative-keys + +struct TestAlternativeKeys: ExAutoCodable, Equatable { + @ExCodable("int", "i") private(set) var int: Int = 0 - var string: String! + @ExCodable("string", "str", "s") private(set) + var string: String! = nil } -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) - // } +// MARK: nested-keys + +struct TestNestedKeys: ExAutoCodable, Equatable { + @ExCodable private(set) + var int: Int = 0 + @ExCodable("nested.nested.string") private(set) + var string: String! = nil } -// MARK: custom encode/decode +// MARK: custom encoding/decoding -struct TestCustomEncodeDecode: Equatable { - var int: Int = 0 - var string: String? +fileprivate func message(for int: Int) -> String { + switch int { + case 100: return "Continue" + case 200: return "OK" + case 304: return "Not Modified" + case 403: return "Forbidden" + case 404: return "Not Found" + case 418: return "I'm a teapot" + case 500: return "Internal Server Error" + case 200..<400: return "success" + default: return "failure" + } } -extension TestCustomEncodeDecode: ExCodable { +struct TestCustomEncodeDecode: ExAutoCodable, Equatable { - private enum Keys: CodingKey { - case int, string - } - private static let dddd = "dddd" - private func string(for int: Int) -> String { - switch int { - case 100: return "Continue" - case 200: return "OK" - case 304: return "Not Modified" - case 403: return "Forbidden" - case 404: return "Not Found" - case 418: return "I'm a teapot" - case 500: return "Internal Server Error" - case 200..<400: return "success" - default: return "failure" + @ExCodable(encode: { encoder, value in + encoder["int"] = value <= 0 ? 0 : value + }, decode: { decoder in + if let int: Int = decoder["int"], int > 0 { + return int } - } - - static let keyMapping: [KeyMap] = [ - KeyMap(\.int, to: Keys.int), - ] + return 0 + }) private(set) + var int: Int = 0 - init(from decoder: Decoder) throws { - try decode(from: decoder, with: Self.keyMapping) - string = decoder[Keys.string] - if string == nil || string == Self.dddd { - string = string(for: int) + @ExCodable(encode: { encoder, value in + encoder["nested.nested.string"] = "" + }, decode: { decoder in + if let string: String = decoder["nested.nested.string"], + string != "" { + return string } - } - func encode(to encoder: Encoder) throws { - try encode(to: encoder, with: Self.keyMapping) - encoder[Keys.string] = Self.dddd - } + if let int: Int = decoder["int"] { + return message(for: int) + } + return nil + }) private(set) + var string: String? = nil + + @ExCodable(encode: { encoder, value in encoder["bool"] = value }, + decode: { decoder in return decoder["bool"/*, converter: Self.self*/] }) private(set) + var bool: Bool = false } // MARK: let + subscripts + CodingKey, without default values @@ -186,7 +181,7 @@ struct TestSubscript: Equatable { let string: String } -extension TestSubscript: Encodable, Decodable { +extension TestSubscript: Codable { enum Keys: CodingKey { case int, string @@ -194,17 +189,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, converter: Self.self)! + // string = try decoder.decodeThrows(Keys.string, as: String.self, converter: Self.self)! + // string = try decoder.decodeNonnullThrows(Keys.string, as: String.self, converter: Self.self) + int = decoder[Keys.int/*, converter: Self.self*/] ?? 0 + string = decoder[Keys.string/*, converter: 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 } @@ -212,6 +207,13 @@ extension TestSubscript: Encodable, Decodable { // MARK: type-conversions +struct TestTypeConversion: ExAutoCodable, Equatable { + @ExCodable private(set) + var intFromString: Int? = nil + @ExCodable private(set) + var stringFromInt: String??? = nil +} + struct TestTypeConversions: Equatable { let boolFromInt, boolFromString: Bool? let intFromBool, intFromDouble, intFromString: Int? @@ -233,20 +235,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/*, converter: Self.self*/] + boolFromString = decoder[Keys.boolFromString/*, converter: Self.self*/] + intFromBool = decoder[Keys.intFromBool/*, converter: Self.self*/] + intFromDouble = decoder[Keys.intFromDouble/*, converter: Self.self*/] + intFromString = decoder[Keys.intFromString/*, converter: Self.self*/] + uIntFromBool = decoder[Keys.uIntFromBool/*, converter: Self.self*/] + uIntFromString = decoder[Keys.uIntFromString/*, converter: Self.self*/] + doubleFromInt64 = decoder[Keys.doubleFromInt64/*, converter: Self.self*/] + doubleFromString = decoder[Keys.doubleFromString/*, converter: Self.self*/] + floatFromInt64 = decoder[Keys.floatFromInt64/*, converter: Self.self*/] + floatFromString = decoder[Keys.floatFromString/*, converter: Self.self*/] + stringFromBool = decoder[Keys.stringFromBool/*, converter: Self.self*/] + stringFromInt64 = decoder[Keys.stringFromInt64/*, converter: Self.self*/] + stringFromDouble = decoder[Keys.stringFromDouble/*, converter: Self.self*/] } func encode(to encoder: Encoder) throws { @@ -269,85 +271,66 @@ extension TestTypeConversions: Encodable, Decodable { // MARK: custom type-conversions -// @available(*, deprecated) -// extension KeyedDecodingContainer: KeyedDecodingContainerCustomTypeConversion { -// public func decodeForTypeConversion(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? where T: Decodable, K: CodingKey { -// -// if type is Double.Type || type is Double?.Type { -// if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey as! Self.Key) { -// return (bool ? 1.0 : 0.0) as? T -// } -// } -// -// else if type is Float.Type || type is Float?.Type { -// if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey as! Self.Key) { -// return (bool ? 1.0 : 0.0) as? T -// } -// } -// -// return nil -// } -// } - -struct FloatToBoolDecodingTypeConverter: ExCodableDecodingTypeConverter { - public func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { - // Bool -> Double - if type is Double.Type || type is Double?.Type { +struct TestCustomTypeConverter: ExAutoCodable, Equatable { + @ExCodable private(set) + var doubleFromBool: Double? = nil + @ExCodable private(set) + var boolFromDouble: Bool? = nil +} + +extension TestCustomTypeConverter: ExCodableDecodingTypeConverter { + public static func decode(_ container: KeyedDecodingContainer, codingKey: K, as type: T.Type) -> T? { + + // for nested optionals, e.g. `var int: Int??? = nil` + let wrappedType = T?.wrappedType + + // decode Double from Bool + if type is Double.Type || wrappedType 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 { + // decode Float from Bool + else if type is Float.Type || wrappedType 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 } } -struct TestCustomTypeConverter: Equatable { - 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) +extension ExCodableGlobalDecodingTypeConverter: ExCodableDecodingTypeConverter { + public static func decode(_ container: KeyedDecodingContainer<_K>, codingKey: _K, as type: T.Type) -> T? { + + // for nested optionals, e.g. `var int: Int??? = nil` + let wrappedType = T?.wrappedType + + // decode Bool from Double + if type is Bool.Type || wrappedType is Bool.Type { + if let double = try? container.decodeIfPresent(Double.self, forKey: codingKey) { + return (double != 0) as? T + } + } + + return nil } - // func encode(to encoder: Encoder) throws { - // try encode(to: encoder, with: Self.keyMapping) - // } } // MARK: class -class TestClass: ExCodable, Equatable { - +class TestClass: ExAutoCodable, Equatable { + @ExCodable private(set) var int: Int = 0 + @ExCodable private(set) var string: String? = nil + + required init() {} 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) - } - // 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,52 +339,48 @@ class TestClass: ExCodable, Equatable { // MARK: subclass class TestSubclass: TestClass { + + @ExCodable private(set) var bool: Bool = false + + required init() { super.init() } 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 { - 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) } } -// MARK: ExCodable +// MARK: nonnull and `throws` -struct TestExCodable: Equatable { - private(set) var int: Int = 0 - private(set) var string: String? +struct TestNonnull: ExAutoCodable, Equatable { + @ExCodable("int", nonnull: true) private(set) + var nonnullInt: Int! = 0 } -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) - // } +struct TestNestedNonnull: ExAutoCodable, Equatable { + @ExCodable("nested.int", "int", nonnull: true) private(set) + var nonnullInt: Int! = 0 +} + +struct TestThrows: ExAutoCodable, Equatable { + @ExCodable("string", "nested.string", throws: true) private(set) + var throwsString: String! = "" +} + +struct TestNestedThrows: ExAutoCodable, Equatable { + @ExCodable("nested.string", "string", throws: true) private(set) + var throwsString: String! = "" +} + +struct TestNonnullWithThrows: ExAutoCodable, Equatable { + @ExCodable("throws", nonnull: true) private(set) + var testThrows: TestThrows! = nil } // MARK: - Tests @@ -411,8 +390,8 @@ final class ExCodableTests: XCTestCase { func testAutoCodable() { 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 copy = try? TestAutoCodable.decoded(from: data), + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { XCTAssertEqual(copy, test) XCTAssertEqual(NSDictionary(dictionary: json), ["i": 100, "s": "Continue"]) } @@ -422,12 +401,29 @@ final class ExCodableTests: XCTestCase { } func testManualCodable() { - let json = Data(#"{"i":200,"nested":{"string":"OK"}}"#.utf8) + let json = Data(#"{"int":200,"nested":{"nested":{"string":"OK"}}}"#.utf8) + // decoded with type-inference if let test = try? json.decoded() as TestManualCodable, let data = try? test.encoded() as Data, let copy = try? data.decoded() as TestManualCodable { XCTAssertEqual(copy, test) - XCTAssertEqual(data, Data(#"{"int":200,"nested":{"string":"OK"}}"#.utf8)) + let json = try! JSONSerialization.jsonObject(with: data) as! [String: Any] + XCTAssertEqual(NSDictionary(dictionary: json), ["int":200,"nested":["nested":["string":"OK"]]]) + } + else { + XCTFail() + } + } + + @available(*, deprecated) + func testExCodable_0_x() { + let json = Data(#"{"int":200,"string":"OK"}"#.utf8) + if let test = try? TestExCodable_0_x.decoded(from: json), + let data = try? test.encoded() as Data, + let copy = try? TestExCodable_0_x.decoded(from: data) { + XCTAssertEqual(copy, test) + let json = try! JSONSerialization.jsonObject(with: data) as! [String: Any] + XCTAssertEqual(NSDictionary(dictionary: json), ["int":200,"string":"OK"]) } else { XCTFail() @@ -435,12 +431,68 @@ final class ExCodableTests: XCTestCase { } func testStruct() { - let test = TestStruct(int: 304, string: "Not Modified") + let test = TestStruct(int: 304, string: "Not Modified"), + test2 = TestStruct(int: 304, string: "Not Modified", bool: nil) + if let dict = try? test.encoded() as [String: Any], + let copy = try? TestStruct.decoded(from: dict), + let copy2 = try? TestStruct.decoded(from: dict) { + XCTAssertEqual(copy, test) + XCTAssertEqual(copy2, test2) + + let string = "string: \(test)" + print(string) + print(test) + debugPrint(test) + } + else { + XCTFail() + } + } + + func testStructWithEnum() { + let test = TestStructWithEnum(enum: .one) if let data = try? test.encoded() as Data, - let copy1 = try? data.decoded() as TestStruct, - let copy2 = try? TestStruct.decoded(from: data) { + let copy1 = try? TestStructWithEnum.decoded(from: data), + 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? TestStructWithEnum.decoded(from: json), + let data = try? test.encoded() as Data, + let copy = try? TestStructWithEnum.decoded(from: data) { + 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? TestStructWithEnum.decoded(from: json), + let data = try? test.encoded() as Data, + let copy = try? TestStructWithEnum.decoded(from: data) { + 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() @@ -449,16 +501,15 @@ final class ExCodableTests: XCTestCase { func testAlternativeKeys() { let json = Data(#"{"i":403,"s":"Forbidden"}"#.utf8) - if let test = try? json.decoded() as TestAlternativeKeys, + if let test = try? TestAlternativeKeys.decoded(from: json), let data = try? test.encoded() as Data, - let copy = try? data.decoded() as TestAlternativeKeys { + let copy = try? TestAlternativeKeys.decoded(from: data) { XCTAssertEqual(test, TestAlternativeKeys(int: 403, string: "Forbidden")) XCTAssertEqual(copy, test) - let localJSON: [String: Any] = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] + 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 { @@ -469,14 +520,16 @@ final class ExCodableTests: XCTestCase { func testNestedKeys() { let test = TestNestedKeys(int: 404, string: "Not Found") if let data = try? test.encoded() as Data, - let copy = try? data.decoded() as TestNestedKeys { + let copy = try? TestNestedKeys.decoded(from: data) { XCTAssertEqual(copy, test) - let json: [String: Any] = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] + let json = try! JSONSerialization.jsonObject(with: data) as! [String: Any] debugPrint(json) XCTAssertEqual(NSDictionary(dictionary: json), [ "int": 404, "nested": [ - "string": "Not Found" + "nested": [ + "string": "Not Found" + ] ] ]) } @@ -486,15 +539,20 @@ 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 { + let copy = try? TestCustomEncodeDecode.decoded(from: data) { XCTAssertEqual(copy, test) - let json: [String: Any] = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] + let json = try! JSONSerialization.jsonObject(with: data) as! [String: Any] debugPrint(json) XCTAssertEqual(NSDictionary(dictionary: json), [ "int": 418, - "string": "dddd" + "nested": [ + "nested": [ + "string": "" + ] + ], + "bool": true ]) } else { @@ -505,7 +563,7 @@ final class ExCodableTests: XCTestCase { func testSubscript() { let test = TestSubscript(int: 500, string: "Internal Server Error") if let data = try? test.encoded() as Data, - let copy = try? data.decoded() as TestSubscript { + let copy = try? TestSubscript.decoded(from: data) { XCTAssertEqual(copy, test) } else { @@ -513,6 +571,48 @@ final class ExCodableTests: XCTestCase { } } + func testTypeConversion() { + + let data = Data(#""" + { + "intFromString": "123", + "stringFromInt": 456 + } + """#.utf8) + + if let test = try? TestTypeConversion.decoded(from: data) { + XCTAssertEqual(test, TestTypeConversion(intFromString: 123, stringFromInt: "456")) + } + else { + XCTFail() + } + + let data2 = Data(#""" + { + "stringFromInt64": 123 + } + """#.utf8) + if let test2 = try? TestTypeConversions.decoded(from: data2) { + XCTAssertEqual(test2, TestTypeConversions(boolFromInt: nil, + boolFromString: nil, + intFromBool: nil, + intFromDouble: nil, + intFromString: nil, + uIntFromBool: nil, + uIntFromString: nil, + doubleFromInt64: nil, + doubleFromString: nil, + floatFromInt64: nil, + floatFromString: nil, + stringFromBool: nil, + stringFromInt64: "123", + stringFromDouble: nil)) + } + else { + XCTFail() + } + } + func testTypeConversions() { let data = Data(#""" @@ -533,7 +633,7 @@ final class ExCodableTests: XCTestCase { "stringFromDouble": 12.3 } """#.utf8) - if let test = try? data.decoded() as TestTypeConversions { + if let test = try? TestTypeConversions.decoded(from: data) { XCTAssertEqual(test, TestTypeConversions(boolFromInt: true, boolFromString: true, intFromBool: 1, @@ -571,7 +671,7 @@ final class ExCodableTests: XCTestCase { "stringFromDouble": 12.3 } """#.utf8) - if let test2 = try? data2.decoded() as TestTypeConversions { + if let test2 = try? TestTypeConversions.decoded(from: data2) { XCTAssertEqual(test2, TestTypeConversions(boolFromInt: false, boolFromString: nil, intFromBool: 0, @@ -593,14 +693,14 @@ final class ExCodableTests: XCTestCase { } func testCustomTypeConverter() { - register(FloatToBoolDecodingTypeConverter()) let data = Data(#""" { - "doubleFromBool": true + "doubleFromBool": true, + "boolFromDouble": 1.2 } """#.utf8) - if let test = try? data.decoded() as TestCustomTypeConverter { - XCTAssertEqual(test, TestCustomTypeConverter(doubleFromBool: 1.0)) + if let test = try? TestCustomTypeConverter.decoded(from: data) { + XCTAssertEqual(test, TestCustomTypeConverter(doubleFromBool: 1.0, boolFromDouble: true)) } else { XCTFail() @@ -610,7 +710,7 @@ final class ExCodableTests: XCTestCase { func testClass() { let test = TestClass(int: 502, string: "Bad Gateway") if let data = try? test.encoded() as Data, - let copy = try? data.decoded() as TestClass { + let copy = try? TestClass.decoded(from: data) { XCTAssertEqual(copy, test) } else { @@ -621,7 +721,7 @@ final class ExCodableTests: XCTestCase { func testSubclass() { let test = TestSubclass(int: 504, string: "Gateway Timeout", bool: true) if let data = try? test.encoded() as Data, - let copy = try? data.decoded() as TestSubclass { + let copy = try? TestSubclass.decoded(from: data) { XCTAssertEqual(copy, test) } else { @@ -629,6 +729,106 @@ final class ExCodableTests: XCTestCase { } } + func testNonnullAndThrows() { + + let noIntData = Data(#""" + { + "noInt": true + } + """#.utf8) + XCTAssertThrowsError(try TestNonnull.decoded(from: noIntData)) { error in + XCTAssertNotNil(error) + print("TestNonnull error: \(error)") + } + XCTAssertThrowsError(try TestNestedNonnull.decoded(from: noIntData)) { error in + XCTAssertNotNil(error) + print("TestNestedNonnull error: \(error)") + } + + let nullData = Data(#""" + { + "int": null, + "nested": { + "int": null + } + } + """#.utf8) + XCTAssertThrowsError(try TestNonnull.decoded(from: nullData)) { error in + XCTAssertNotNil(error) + print("TestNonnull error: \(error)") + } + XCTAssertThrowsError(try TestNestedNonnull.decoded(from: nullData)) { error in + XCTAssertNotNil(error) + print("TestNestedNonnull error: \(error)") + } + + let nonnullData = Data(#""" + { + "int": 1, + "nested": { + "int": 1 + } + } + """#.utf8) + XCTAssertEqual(try TestNonnull.decoded(from: nonnullData), TestNonnull(nonnullInt: 1)) + XCTAssertEqual(try TestNestedNonnull.decoded(from: nonnullData), TestNestedNonnull(nonnullInt: 1)) + + let throwsData = Data(#""" + { + "string": [], + "nested": { + "string": [] + } + } + """#.utf8) + XCTAssertThrowsError(try TestThrows.decoded(from: throwsData)) { error in + XCTAssertNotNil(error) + print("TestThrows error: \(error)") + } + XCTAssertThrowsError(try TestNestedThrows.decoded(from: throwsData)) { error in + XCTAssertNotNil(error) + print("TestNestedThrows error: \(error)") + } + + let noThrowsData = Data(#""" + { + "string": 123 + } + """#.utf8) + XCTAssertEqual(try TestThrows.decoded(from: noThrowsData), TestThrows(throwsString: "123")) + XCTAssertEqual(try TestNestedThrows.decoded(from: noThrowsData), TestNestedThrows(throwsString: "123")) + + let nonnullWithThrowsData = Data(#""" + { + "throws": { + "string": [] + } + } + """#.utf8) + XCTAssertThrowsError(try TestNonnullWithThrows.decoded(from: nonnullWithThrowsData)) { error in + XCTAssertNotNil(error) + print("TestNonnullWithThrows error: \(error)") + } + + XCTAssertThrowsError(try TestNonnull(nonnullInt: nil).encoded() as Data) { error in + XCTAssertNotNil(error) + print("TestNonnull error: \(error)") + } + XCTAssertThrowsError(try TestNestedNonnull(nonnullInt: nil).encoded() as Data) { error in + XCTAssertNotNil(error) + print("TestNestedNonnull error: \(error)") + } + + XCTAssertThrowsError(try TestThrows(throwsString: nil).encoded() as Data) { error in + XCTAssertNotNil(error) + print("TestThrows error: \(error)") + } + XCTAssertThrowsError(try TestNestedThrows(throwsString: nil).encoded() as Data) { error in + XCTAssertNotNil(error) + print("TestNestedThrows error: \(error)") + } + } + func testExCodable() { let array = [ TestExCodable(int: 100, string: "Continue"), @@ -654,7 +854,7 @@ final class ExCodableTests: XCTestCase { ] if let json = try? array.encoded() as Data, - let copies = try? json.decoded() as [TestExCodable], + let copies = try? [TestExCodable].decoded(from: json), let copies2 = try? [TestExCodable].decoded(from: json) { XCTAssertEqual(copies, array) XCTAssertEqual(copies2, array) @@ -663,7 +863,7 @@ final class ExCodableTests: XCTestCase { XCTFail() } if let json = try? array.encoded() as [Any], - let copies = try? json.decoded() as [TestExCodable], + let copies = try? [TestExCodable].decoded(from: json), let copies2 = try? [TestExCodable].decoded(from: json) { XCTAssertEqual(copies, array) XCTAssertEqual(copies2, array) @@ -672,7 +872,7 @@ final class ExCodableTests: XCTestCase { XCTFail() } if let json = try? array.encoded() as String, - let copies = try? json.decoded() as [TestExCodable], + let copies = try? [TestExCodable].decoded(from: json), let copies2 = try? [TestExCodable].decoded(from: json) { XCTAssertEqual(copies, array) XCTAssertEqual(copies2, array) @@ -682,7 +882,7 @@ final class ExCodableTests: XCTestCase { } if let json = try? dictionary.encoded() as Data, - let copies = try? json.decoded() as [String: TestExCodable], + let copies = try? [String: TestExCodable].decoded(from: json), let copies2 = try? [String: TestExCodable].decoded(from: json) { XCTAssertEqual(copies, dictionary) XCTAssertEqual(copies2, dictionary) @@ -691,7 +891,7 @@ final class ExCodableTests: XCTestCase { XCTFail() } if let json = try? dictionary.encoded() as [String: Any], - let copies = try? json.decoded() as [String: TestExCodable], + let copies = try? [String: TestExCodable].decoded(from: json), let copies2 = try? [String: TestExCodable].decoded(from: json) { XCTAssertEqual(copies, dictionary) XCTAssertEqual(copies2, dictionary) @@ -700,7 +900,7 @@ final class ExCodableTests: XCTestCase { XCTFail() } if let json = try? dictionary.encoded() as String, - let copies = try? json.decoded() as [String: TestExCodable], + let copies = try? [String: TestExCodable].decoded(from: json), let copies2 = try? [String: TestExCodable].decoded(from: json) { XCTAssertEqual(copies, dictionary) XCTAssertEqual(copies2, dictionary) @@ -710,18 +910,42 @@ final class ExCodableTests: XCTestCase { } } - 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), - ] + func testElapsed() { + let start = DispatchTime.now().uptimeNanoseconds + + for _ in 0..<1_0000 { + let test = TestStruct(int: 304, string: "Not Modified") + if let data = try? test.encoded() as Data, + let copy = try? TestStruct.decoded(from: data) { + XCTAssertEqual(copy, test) + } + else { + XCTFail() + } + + let test2 = TestClass(int: 502, string: "Bad Gateway") + if let data = try? test2.encoded() as Data, + let copy = try? TestClass.decoded(from: data) { + XCTAssertEqual(copy, test2) + } + else { + XCTFail() + } + + let test3 = TestSubclass(int: 504, string: "Gateway Timeout", bool: true) + if let data = try? test3.encoded() as Data, + let copy = try? TestSubclass.decoded(from: data) { + XCTAssertEqual(copy, test3) + } + else { + XCTFail() + } + } + + let elapsed = DispatchTime.now().uptimeNanoseconds - start + // let seconds = elapsed / 1_000_000_000 + let milliseconds = elapsed / 1_000_000 + print("elapsed: \(milliseconds) ms") + // TODO: compare to builtin and 0.x + } } 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)