├── .gitignore
├── .jazzy.yaml
├── .swift-version
├── .travis.yml
├── LICENSE.txt
├── Package.swift
├── README.md
├── Sources
└── TypeDecoder
│ ├── OrderedDictionary.swift
│ └── TypeDecoder.swift
├── Tests
├── LinuxMain.swift
└── TypeDecoderTests
│ ├── OrderedDictionaryTests.swift
│ ├── TypeDecoderTests.swift
│ └── TypeDecodingErrorTests.swift
├── docs
├── Enums.html
├── Enums
│ └── TypeInfo.html
├── Extensions.html
├── Extensions
│ ├── TimeZone.html
│ ├── URL.html
│ └── UUID.html
├── Protocols.html
├── Protocols
│ ├── ValidKeyedCodingValueProvider.html
│ └── ValidSingleCodingValueProvider.html
├── Structs.html
├── Structs
│ ├── OrderedDictionary.html
│ ├── TypeDecoder.html
│ └── TypeDecodingError.html
├── badge.svg
├── css
│ ├── highlight.css
│ └── jazzy.css
├── docsets
│ ├── TypeDecoder.docset
│ │ └── Contents
│ │ │ ├── Info.plist
│ │ │ └── Resources
│ │ │ ├── Documents
│ │ │ ├── Enums.html
│ │ │ ├── Enums
│ │ │ │ └── TypeInfo.html
│ │ │ ├── Extensions.html
│ │ │ ├── Extensions
│ │ │ │ ├── TimeZone.html
│ │ │ │ ├── URL.html
│ │ │ │ └── UUID.html
│ │ │ ├── Protocols.html
│ │ │ ├── Protocols
│ │ │ │ ├── ValidKeyedCodingValueProvider.html
│ │ │ │ └── ValidSingleCodingValueProvider.html
│ │ │ ├── Structs.html
│ │ │ ├── Structs
│ │ │ │ ├── OrderedDictionary.html
│ │ │ │ ├── TypeDecoder.html
│ │ │ │ └── TypeDecodingError.html
│ │ │ ├── css
│ │ │ │ ├── highlight.css
│ │ │ │ └── jazzy.css
│ │ │ ├── img
│ │ │ │ ├── carat.png
│ │ │ │ ├── dash.png
│ │ │ │ ├── gh.png
│ │ │ │ └── spinner.gif
│ │ │ ├── index.html
│ │ │ ├── js
│ │ │ │ ├── jazzy.js
│ │ │ │ ├── jazzy.search.js
│ │ │ │ ├── jquery.min.js
│ │ │ │ ├── lunr.min.js
│ │ │ │ └── typeahead.jquery.js
│ │ │ └── search.json
│ │ │ └── docSet.dsidx
│ └── TypeDecoder.tgz
├── img
│ ├── carat.png
│ ├── dash.png
│ ├── gh.png
│ └── spinner.gif
├── index.html
├── js
│ ├── jazzy.js
│ ├── jazzy.search.js
│ ├── jquery.min.js
│ ├── lunr.min.js
│ └── typeahead.jquery.js
├── search.json
└── undocumented.json
└── sonar-project.properties
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | /.build
3 | /Packages
4 | /*.xcodeproj
5 |
--------------------------------------------------------------------------------
/.jazzy.yaml:
--------------------------------------------------------------------------------
1 | module: TypeDecoder
2 | author: IBM & Kitura Project Contributors
3 | github_url: https://github.com/Kitura/TypeDecoder
4 |
5 | theme: fullwidth
6 | clean: true
7 | exclude: [Packages]
8 |
9 | readme: README.md
10 |
11 | skip_undocumented: false
12 | hide_documentation_coverage: false
13 |
14 |
--------------------------------------------------------------------------------
/.swift-version:
--------------------------------------------------------------------------------
1 | 5.1
2 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | # Travis CI build file.
2 |
3 | # whitelist (branches that should be built)
4 | branches:
5 | only:
6 | - master
7 | - /^issue.*$/
8 |
9 | # the matrix of builds should cover each combination of Swift version
10 | # and platform that is supported. The version of Swift used is specified
11 | # by .swift-version, unless SWIFT_SNAPSHOT is specified.
12 | matrix:
13 | include:
14 | - os: linux
15 | dist: xenial
16 | sudo: required
17 | services: docker
18 | env: DOCKER_IMAGE=docker.kitura.net/kitura/swift-ci-ubuntu16.04:5.1.5
19 | - os: linux
20 | dist: bionic
21 | sudo: required
22 | services: docker
23 | env: DOCKER_IMAGE=docker.kitura.net/kitura/swift-ci-ubuntu18.04:5.4
24 | - os: linux
25 | dist: xenial
26 | sudo: required
27 | services: docker
28 | env: DOCKER_IMAGE=docker.kitura.net/kitura/swift-ci-ubuntu18.04:latest USE_SWIFT_DEVELOPMENT_SNAPSHOT=1
29 | - os: osx
30 | osx_image: xcode11
31 | sudo: required
32 | env: SWIFT_SNAPSHOT=5.1.5 JAZZY_ELIGIBLE=true
33 | - os: osx
34 | osx_image: xcode12.2
35 | sudo: required
36 | - os: osx
37 | osx_image: xcode12.5
38 | sudo: required
39 | env: USE_SWIFT_DEVELOPMENT_SNAPSHOT=1
40 |
41 | before_install:
42 | - git clone https://github.com/Kitura/Package-Builder.git
43 |
44 | script:
45 | - ./Package-Builder/build-package.sh -projectDir $TRAVIS_BUILD_DIR
46 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
--------------------------------------------------------------------------------
/Package.swift:
--------------------------------------------------------------------------------
1 | // swift-tools-version:5.0
2 | // The swift-tools-version declares the minimum version of Swift required to build this package.
3 |
4 | import PackageDescription
5 |
6 | let package = Package(
7 | name: "TypeDecoder",
8 | products: [
9 | // Products define the executables and libraries produced by a package, and make them visible to other packages.
10 | .library(
11 | name: "TypeDecoder",
12 | targets: ["TypeDecoder"]),
13 | ],
14 | dependencies: [
15 | // Dependencies declare other packages that this package depends on.
16 | // .package(url: /* package url */, from: "1.0.0"),
17 | ],
18 | targets: [
19 | // Targets are the basic building blocks of a package. A target can define a module or a test suite.
20 | // Targets can depend on other targets in this package, and on products in packages which this package depends on.
21 | .target(
22 | name: "TypeDecoder",
23 | dependencies: []),
24 | .testTarget(
25 | name: "TypeDecoderTests",
26 | dependencies: ["TypeDecoder"]),
27 | ]
28 | )
29 |
--------------------------------------------------------------------------------
/Sources/TypeDecoder/OrderedDictionary.swift:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright IBM Corporation 2018
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | ///
18 | public struct OrderedDictionary {
19 | private var keys: Array = []
20 | private var values: Dictionary = [:]
21 | private var iteratorCount = 0
22 |
23 | /// `OrderedDictionary` constructor.
24 | public init() {}
25 |
26 | /// Read only property that provides the number of elements in the `OrderedDictionary`.
27 | public var count: Int {
28 | get {
29 | return self.keys.count
30 | }
31 | }
32 |
33 | /// Provides a way to add and remove elements from the
34 | /// `OrderedDictionary`, just like any other `Dictionary`.
35 | ///
36 | /// Setting an element to nil will remove it from the `OrderedDictionary`.
37 | public subscript(key: K) -> V? {
38 | get {
39 | return self.values[key]
40 | }
41 | set(value) {
42 | if let new = value {
43 | let old = self.values.updateValue(new, forKey: key)
44 | if old == nil {
45 | self.keys.append(key)
46 | }
47 | self.iteratorCount = self.keys.count
48 | return
49 | }
50 | self.values.removeValue(forKey: key)
51 | self.keys = self.keys.filter {$0 != key}
52 | self.iteratorCount = self.keys.count
53 | return
54 | }
55 | }
56 |
57 | /// Return the element value at the numeric index specified.
58 | public subscript(index: Int) -> V? {
59 | if self.keys.indices.contains(index) {
60 | let key = self.keys[index]
61 | return self.values[key]
62 | }
63 | return nil
64 | }
65 |
66 | /// Read only property that provides a String containing the key:value pairs in the `OrderedDictionary`.
67 | public var description: String {
68 | var result = ""
69 | for (k, v) in self {
70 | result += "\(k): \(v)\n"
71 | }
72 | return result
73 | }
74 |
75 | }
76 |
77 | extension OrderedDictionary: Sequence, IteratorProtocol {
78 | /// Method to allow iteration over the contents of the
79 | /// `OrderedDictionary`. This method ensures that items are read in the same
80 | /// sequence as they were added.
81 | public mutating func next() -> (K, V)? {
82 | if self.iteratorCount == 0 {
83 | return nil
84 | } else {
85 | defer { self.iteratorCount -= 1 }
86 | let theKey = self.keys[self.keys.count - self.iteratorCount]
87 | let theValue = self.values[theKey]
88 | if let unwrappedValue = theValue {
89 | return(theKey, unwrappedValue)
90 | }
91 | return nil
92 | }
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/Tests/LinuxMain.swift:
--------------------------------------------------------------------------------
1 | import XCTest
2 | @testable import TypeDecoderTests
3 |
4 | XCTMain([
5 | testCase(TypeDecoderTests.allTests),
6 | testCase(OrderedDictionaryTests.allTests),
7 | testCase(TypeDecodingErrorTests.allTests),
8 | ])
9 |
--------------------------------------------------------------------------------
/Tests/TypeDecoderTests/OrderedDictionaryTests.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import XCTest
3 | @testable import TypeDecoder
4 |
5 | class OrderedDictionaryTests: XCTestCase {
6 |
7 | static var allTests = [
8 | ("testIterator", testIterator),
9 | ("testElementRemoval", testElementRemoval),
10 | ("testElementReplacement", testElementReplacement),
11 | ("testGetWithIntIndex", testGetWithIntIndex),
12 | ("testDescription", testDescription),
13 | ]
14 |
15 | func testIterator() {
16 | // Test that elements are found in the correct sequence.
17 | let keys = ["one", "two", "three", "four"]
18 | let values = ["1", "2", "3", "4"]
19 | var dict = OrderedDictionary()
20 | var count = 0
21 | dict["one"] = "1"
22 | dict["two"] = "2"
23 | dict["three"] = "3"
24 | dict["four"] = "4"
25 |
26 | for (k, v) in dict {
27 | if keys[count] != k {
28 | XCTFail("key: \(keys[count]) not found or in wrong position")
29 | if values[count] != String(describing: v) {
30 | XCTFail("value: \(values[count]) not found or in wrong position")
31 | }
32 | }
33 | count += 1
34 | }
35 | }
36 |
37 | func testElementRemoval() {
38 | // Test that setting an element to nil remove it
39 | var dict = OrderedDictionary()
40 | dict["one"] = "1"
41 | dict["two"] = "2"
42 | dict["three"] = "3"
43 | dict["four"] = "4"
44 | dict["three"] = nil
45 |
46 | XCTAssertTrue(dict.count == 3, "wrong number of elements in dict, found \(dict.count), should have found 3")
47 | XCTAssertTrue(dict["three"] == nil, "failed to remove an element from dict")
48 | }
49 |
50 | func testElementReplacement() {
51 | // Test that an element can be replaced.
52 | var dict = OrderedDictionary()
53 | dict["one"] = "1"
54 | dict["two"] = "2"
55 | dict["two"] = "2+2"
56 |
57 | XCTAssertTrue(dict["two"] == "2+2", "failed to replace an element in dict")
58 | }
59 |
60 | func testGetWithIntIndex() {
61 | // Test that an element can be replaced.
62 | var dict = OrderedDictionary()
63 | dict["one"] = "1"
64 | dict["two"] = "2"
65 | dict["three"] = "2+1"
66 |
67 | XCTAssertTrue(dict[0] == "1", "failed to get the correct element at index 0")
68 | XCTAssertTrue(dict[1] == "2", "failed to get the correct element at index 1")
69 | XCTAssertTrue(dict[2] == "2+1", "failed to get the correct element at index 2")
70 | XCTAssertTrue(dict[3] == nil, "failed to get nil element at out of range index")
71 | }
72 |
73 | func testDescription() {
74 | // Test that the description method returns a meaningful string.
75 | var dict = OrderedDictionary()
76 | let testDesc = """
77 | one: 1
78 | two: 2
79 | three: 3
80 |
81 | """
82 |
83 | dict["one"] = "1"
84 | dict["two"] = "2"
85 | dict["three"] = "3"
86 |
87 | XCTAssertEqual(dict.description, testDesc)
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/Tests/TypeDecoderTests/TypeDecodingErrorTests.swift:
--------------------------------------------------------------------------------
1 | import Foundation
2 | import XCTest
3 | @testable import TypeDecoder
4 |
5 | class TypeDecodingErrorTests: XCTestCase {
6 |
7 | static var allTests = [
8 | ("testDecodeErrorSingle", testDecodeErrorSingle),
9 | ("testDecodeErrorValidSingle", testDecodeErrorValidSingle),
10 | ("testDecodeValidSingleSuccess", testDecodeValidSingleSuccess),
11 | ("testDecodeErrorKeyed", testDecodeErrorKeyed),
12 | ("testDecodeErrorValidKeyed", testDecodeErrorValidKeyed),
13 | ("testDecodeValidKeyedSuccess", testDecodeValidKeyedSuccess),
14 | ]
15 |
16 | // A simple Codable enum with String raw value. The TypeDecoder cannot
17 | // handle this as-is, and decoding is expected to fail.
18 | enum CodableEnum: String, Codable {
19 | case foo,bar
20 | }
21 |
22 | // A simple Codable enum with String raw value, with conformance to
23 | // ValidSingleCodingValueProvider in order to provide a value. The value
24 | // provided in this case is invalid (decoding should fail).
25 | enum CodableValidEnumFail: String, Codable, ValidSingleCodingValueProvider {
26 | case foo,bar
27 | static func validCodingValue() -> Any? {
28 | return "fail"
29 | }
30 | }
31 |
32 | // A simple Codable enum with String raw value, with conformance to
33 | // ValidSingleCodingValueProvider in order to provide a value. The value
34 | // provided in this case is acceptable (decoding should succeed).
35 | enum CodableValidEnum: String, Codable, ValidSingleCodingValueProvider {
36 | case foo,bar
37 | static func validCodingValue() -> Any? {
38 | return self.foo.rawValue
39 | }
40 | }
41 |
42 | // A Codable struct with a validated String field. The TypeDecoder cannot
43 | // handle this as-is, and decoding is expected to fail.
44 | struct CodableKeyed: Codable {
45 | let foo: String
46 | public init(from decoder: Decoder) throws {
47 | let container = try decoder.container(keyedBy: CodingKeys.self)
48 | self.foo = try container.decode(String.self, forKey: CodingKeys.foo)
49 | guard self.foo == "Foo" else {
50 | throw DecodingError.dataCorruptedError(forKey: CodingKeys.foo, in: container, debugDescription: "Not Foo")
51 | }
52 | }
53 | }
54 |
55 | // A Codable struct with a validated String field, with conformance to
56 | // ValidKeyedCodingValueProvider in order to provide a value. The value
57 | // provided in this case is invalid (decoding should fail).
58 | struct CodableValidKeyedFail: Codable, ValidKeyedCodingValueProvider {
59 | static func validCodingValue(forKey key: CodingKey) -> Any? {
60 | return "Bar"
61 | }
62 |
63 | let foo: String
64 | public init(from decoder: Decoder) throws {
65 | let container = try decoder.container(keyedBy: CodingKeys.self)
66 | self.foo = try container.decode(String.self, forKey: CodingKeys.foo)
67 | guard self.foo == "Foo" else {
68 | throw DecodingError.dataCorruptedError(forKey: CodingKeys.foo, in: container, debugDescription: "Not Foo")
69 | }
70 | }
71 | }
72 |
73 | // A Codable struct with a validated String field, with conformance to
74 | // ValidKeyedCodingValueProvider in order to provide a value. The value
75 | // provided in this case is acceptable (decoding should succeed).
76 | struct CodableValidKeyed: Codable, ValidKeyedCodingValueProvider {
77 | static func validCodingValue(forKey key: CodingKey) -> Any? {
78 | switch key.stringValue {
79 | case self.CodingKeys.foo.stringValue:
80 | return "Foo"
81 | default:
82 | return nil
83 | }
84 | }
85 |
86 | let foo: String
87 | public init(from decoder: Decoder) throws {
88 | let container = try decoder.container(keyedBy: CodingKeys.self)
89 | self.foo = try container.decode(String.self, forKey: CodingKeys.foo)
90 | guard self.foo == "Foo" else {
91 | throw DecodingError.dataCorruptedError(forKey: CodingKeys.foo, in: container, debugDescription: "Not Foo")
92 | }
93 | }
94 | }
95 |
96 | // Test that decoding a SingleValue type which performs validation
97 | // fails with a TypeDecodingError with Symptom.noValueProvided
98 | func testDecodeErrorSingle() {
99 | do {
100 | let typeInfo = try TypeDecoder.decode(CodableEnum.self)
101 | XCTFail("Expected a TypeDecodingError but unexpectedly succeeded: \(typeInfo.debugDescription)")
102 | } catch let error as TypeDecodingError {
103 | XCTAssertEqual(error.symptom, TypeDecodingError.Symptom.noValueProvided)
104 | } catch {
105 | XCTFail("Expected a TypeDecodingError but received: \(error)")
106 | }
107 | }
108 |
109 | // Test that decoding a SingleValue type which performs validation,
110 | // and provides an invalid dummy value via ValidSingleCodingValueProvider
111 | // fails with a TypeDecodingError with Symptom.invalidSingleValue
112 | func testDecodeErrorValidSingle() {
113 | do {
114 | let typeInfo = try TypeDecoder.decode(CodableValidEnumFail.self)
115 | XCTFail("Expected a TypeDecodingError but unexpectedly succeeded: \(typeInfo.debugDescription)")
116 | } catch let error as TypeDecodingError {
117 | XCTAssertEqual(error.symptom, TypeDecodingError.Symptom.invalidSingleValue)
118 | } catch {
119 | XCTFail("Expected a TypeDecodingError but received: \(error)")
120 | }
121 | }
122 |
123 | // Test that decoding a SingleValue type which performs validation,
124 | // and provides an acceptable dummy value via ValidSingleCodingValueProvider
125 | // succeeds.
126 | func testDecodeValidSingleSuccess() {
127 | do {
128 | let typeInfo = try TypeDecoder.decode(CodableValidEnum.self)
129 | XCTAssertEqual(typeInfo, .single(String.self, String.self))
130 | } catch {
131 | XCTFail("Expected decoding to succeed, but received: \(error)")
132 | }
133 | }
134 |
135 | // Test that decoding a Keyed type which performs validation fails
136 | // with a TypeDecodingError with Symptom.noValueProvided
137 | func testDecodeErrorKeyed() {
138 | do {
139 | let typeInfo = try TypeDecoder.decode(CodableKeyed.self)
140 | XCTFail("Expected a TypeDecodingError but unexpectedly succeeded: \(typeInfo.debugDescription)")
141 | } catch let error as TypeDecodingError {
142 | XCTAssertEqual(error.symptom, TypeDecodingError.Symptom.noValueProvided)
143 | } catch {
144 | XCTFail("Expected a TypeDecodingError but received: \(error)")
145 | }
146 | }
147 |
148 | // Test that decoding a Keyed type which performs validation, and
149 | // provides an invalid dummy value via ValidKeyedCodingValueProvider
150 | // fails with a TypeDecodingError with Symptom.invalidKeyedValue
151 | func testDecodeErrorValidKeyed() {
152 | do {
153 | let typeInfo = try TypeDecoder.decode(CodableValidKeyedFail.self)
154 | XCTFail("Expected a TypeDecodingError but unexpectedly succeeded: \(typeInfo.debugDescription)")
155 | } catch let error as TypeDecodingError {
156 | XCTAssertEqual(error.symptom, TypeDecodingError.Symptom.invalidKeyedValue)
157 | } catch {
158 | XCTFail("Expected a TypeDecodingError but received: \(error)")
159 | }
160 | }
161 |
162 | // Test that decoding a Keyed type which performs validation, and
163 | // provides an acceptable dummy value via ValidKeyedCodingValueProvider
164 | // succeeds.
165 | func testDecodeValidKeyedSuccess() {
166 | do {
167 | let typeInfo = try TypeDecoder.decode(CodableValidKeyed.self)
168 | switch typeInfo {
169 | case .keyed(let type, _):
170 | XCTAssertTrue(type is CodableValidKeyed.Type, "Expected type to be \(CodableValidKeyed.self) but was: \(type)")
171 | default:
172 | XCTFail("Expected decode of keyed type, but was: \(typeInfo.debugDescription)")
173 | }
174 | } catch {
175 | XCTFail("Expected decoding to succeed, but received: \(error)")
176 | }
177 | }
178 |
179 | }
180 |
--------------------------------------------------------------------------------
/docs/Enums.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Enumerations Reference
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
A protocol that your Codable type can adopt, in order to supply a
115 | valid value during decoding. This protocol is suitable for types that
116 | are represented by a single encoded value, such as an enum.
117 |
118 |
The TypeDecoder operates by constructing a ‘dummy’ instance of a type,
119 | via the init(from: Decoder) initializer. As there is no real data to
120 | be decoded, a dummy value (such as 0 or "") is provided. This
121 | may cause an initializer that requires a specific valid value to fail.
122 |
123 |
To enable such a type to work with TypeDecoder, define an extension
124 | that conforms the type to the ValidSingleCodingValueProvider protocol.
125 | The validCodingValue() function should return a valid encoded
126 | representation of that type.
127 |
Usage Example:
128 |
publicenumFruit:String,Codable{
129 | caseapple,banana,orange,pear
130 | }
131 |
132 | // Provide an acceptable value during decoding
133 | extensionFruit:ValidSingleCodingValueProvider{
134 | publicstaticfuncvalidCodingValue()->Any?{
135 | // Returns the string "apple"
136 | returnself.apple.rawValue
137 | }
138 | }
139 |
An Error type indicating a problem during decoding by the TypeDecoder.
115 |
116 |
This type provides additional guidance for Decodable types that do not
117 | conform to either the ValidSingleCodingValueProvider or ValidKeyedCodingValueProvider
118 | protocols, suggesting that conformance may enable successful decoding.
A protocol that your Codable type can adopt, in order to supply a
115 | valid value during decoding. This protocol is suitable for types that
116 | are represented by a single encoded value, such as an enum.
117 |
118 |
The TypeDecoder operates by constructing a ‘dummy’ instance of a type,
119 | via the init(from: Decoder) initializer. As there is no real data to
120 | be decoded, a dummy value (such as 0 or "") is provided. This
121 | may cause an initializer that requires a specific valid value to fail.
122 |
123 |
To enable such a type to work with TypeDecoder, define an extension
124 | that conforms the type to the ValidSingleCodingValueProvider protocol.
125 | The validCodingValue() function should return a valid encoded
126 | representation of that type.
127 |
Usage Example:
128 |
publicenumFruit:String,Codable{
129 | caseapple,banana,orange,pear
130 | }
131 |
132 | // Provide an acceptable value during decoding
133 | extensionFruit:ValidSingleCodingValueProvider{
134 | publicstaticfuncvalidCodingValue()->Any?{
135 | // Returns the string "apple"
136 | returnself.apple.rawValue
137 | }
138 | }
139 |
An Error type indicating a problem during decoding by the TypeDecoder.
115 |
116 |
This type provides additional guidance for Decodable types that do not
117 | conform to either the ValidSingleCodingValueProvider or ValidKeyedCodingValueProvider
118 | protocols, suggesting that conformance may enable successful decoding.
Provides a way to add and remove elements from the","parent_name":"OrderedDictionary"},"Structs/OrderedDictionary.html#/s:11TypeDecoder17OrderedDictionaryVyq_SgSicip":{"name":"subscript(_:)","abstract":"
Return the element value at the numeric index specified.
Method to allow iteration over the contents of the","parent_name":"OrderedDictionary"},"Structs/OrderedDictionary.html":{"name":"OrderedDictionary"},"Structs/TypeDecodingError.html":{"name":"TypeDecodingError","abstract":"
An Error type indicating a problem during decoding by the TypeDecoder.
TypeDecoder allows you to decode a Swift type by using TypeDecoder.decode() and passing the type to"},"Protocols/ValidSingleCodingValueProvider.html#/s:11TypeDecoder30ValidSingleCodingValueProviderP05valideF0ypSgyFZ":{"name":"validCodingValue()","abstract":"
Returns a valid encoded representation of the conforming type.
Returns a value for a CodingKey that represents a field that","parent_name":"ValidKeyedCodingValueProvider"},"Protocols/ValidKeyedCodingValueProvider.html":{"name":"ValidKeyedCodingValueProvider","abstract":"
A protocol that your Codable type can adopt, in order to supply values"},"Protocols/ValidSingleCodingValueProvider.html":{"name":"ValidSingleCodingValueProvider","abstract":"
A protocol that your Codable type can adopt, in order to supply a"},"Extensions/UUID.html#/s:11TypeDecoder30ValidSingleCodingValueProviderP05valideF0ypSgyFZ":{"name":"validCodingValue()","parent_name":"UUID"},"Extensions/TimeZone.html#/s:11TypeDecoder29ValidKeyedCodingValueProviderP05valideF06forKeyypSgs0eJ0_p_tFZ":{"name":"validCodingValue(forKey:)","parent_name":"TimeZone"},"Extensions/URL.html#/s:11TypeDecoder29ValidKeyedCodingValueProviderP05valideF06forKeyypSgs0eJ0_p_tFZ":{"name":"validCodingValue(forKey:)","parent_name":"URL"},"Extensions/URL.html":{"name":"URL","abstract":"
Extension of the URL Foundation class that has validations to provide"},"Extensions/TimeZone.html":{"name":"TimeZone","abstract":"
Extension of the TimeZone Foundation class that has validations to provide"},"Extensions/UUID.html":{"name":"UUID","abstract":"
Extension of the UUID Foundation class that has validations to provide"},"Enums/TypeInfo.html#/s:11TypeDecoder0A4InfoO6singleyACypXp_ypXptcACmF":{"name":"single(_:_:)","abstract":"
Case representing a simple type, such as a String, which is not recursive.
Case representing a struct or a class containing the object type as","parent_name":"TypeInfo"},"Enums/TypeInfo.html#/s:11TypeDecoder0A4InfoO12dynamicKeyedyACypXp_A2CtcACmF":{"name":"dynamicKeyed(_:key:value:)","abstract":"
Case representing a Dictionary containing the top level type of the","parent_name":"TypeInfo"},"Enums/TypeInfo.html#/s:11TypeDecoder0A4InfoO7unkeyedyACypXp_ACtcACmF":{"name":"unkeyed(_:_:)","abstract":"
Case representing an Array containing the top level type of the array","parent_name":"TypeInfo"},"Enums/TypeInfo.html#/s:11TypeDecoder0A4InfoO8optionalyA2CcACmF":{"name":"optional(_:)","abstract":"
Case representing an Optional type containing its nested type.
Provides a way to add and remove elements from the","parent_name":"OrderedDictionary"},"Structs/OrderedDictionary.html#/s:11TypeDecoder17OrderedDictionaryVyq_SgSicip":{"name":"subscript(_:)","abstract":"
Return the element value at the numeric index specified.
Method to allow iteration over the contents of the","parent_name":"OrderedDictionary"},"Structs/OrderedDictionary.html":{"name":"OrderedDictionary"},"Structs/TypeDecodingError.html":{"name":"TypeDecodingError","abstract":"
An Error type indicating a problem during decoding by the TypeDecoder.
TypeDecoder allows you to decode a Swift type by using TypeDecoder.decode() and passing the type to"},"Protocols/ValidSingleCodingValueProvider.html#/s:11TypeDecoder30ValidSingleCodingValueProviderP05valideF0ypSgyFZ":{"name":"validCodingValue()","abstract":"
Returns a valid encoded representation of the conforming type.
Returns a value for a CodingKey that represents a field that","parent_name":"ValidKeyedCodingValueProvider"},"Protocols/ValidKeyedCodingValueProvider.html":{"name":"ValidKeyedCodingValueProvider","abstract":"
A protocol that your Codable type can adopt, in order to supply values"},"Protocols/ValidSingleCodingValueProvider.html":{"name":"ValidSingleCodingValueProvider","abstract":"
A protocol that your Codable type can adopt, in order to supply a"},"Extensions/UUID.html#/s:11TypeDecoder30ValidSingleCodingValueProviderP05valideF0ypSgyFZ":{"name":"validCodingValue()","parent_name":"UUID"},"Extensions/TimeZone.html#/s:11TypeDecoder29ValidKeyedCodingValueProviderP05valideF06forKeyypSgs0eJ0_p_tFZ":{"name":"validCodingValue(forKey:)","parent_name":"TimeZone"},"Extensions/URL.html#/s:11TypeDecoder29ValidKeyedCodingValueProviderP05valideF06forKeyypSgs0eJ0_p_tFZ":{"name":"validCodingValue(forKey:)","parent_name":"URL"},"Extensions/URL.html":{"name":"URL","abstract":"
Extension of the URL Foundation class that has validations to provide"},"Extensions/TimeZone.html":{"name":"TimeZone","abstract":"
Extension of the TimeZone Foundation class that has validations to provide"},"Extensions/UUID.html":{"name":"UUID","abstract":"
Extension of the UUID Foundation class that has validations to provide"},"Enums/TypeInfo.html#/s:11TypeDecoder0A4InfoO6singleyACypXp_ypXptcACmF":{"name":"single(_:_:)","abstract":"
Case representing a simple type, such as a String, which is not recursive.
Case representing a struct or a class containing the object type as","parent_name":"TypeInfo"},"Enums/TypeInfo.html#/s:11TypeDecoder0A4InfoO12dynamicKeyedyACypXp_A2CtcACmF":{"name":"dynamicKeyed(_:key:value:)","abstract":"
Case representing a Dictionary containing the top level type of the","parent_name":"TypeInfo"},"Enums/TypeInfo.html#/s:11TypeDecoder0A4InfoO7unkeyedyACypXp_ACtcACmF":{"name":"unkeyed(_:_:)","abstract":"
Case representing an Array containing the top level type of the array","parent_name":"TypeInfo"},"Enums/TypeInfo.html#/s:11TypeDecoder0A4InfoO8optionalyA2CcACmF":{"name":"optional(_:)","abstract":"
Case representing an Optional type containing its nested type.