-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathExCodable.swift
More file actions
679 lines (602 loc) · 36.5 KB
/
ExCodable.swift
File metadata and controls
679 lines (602 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
//
// ExCodable.swift
// ExCodable
//
// Created by Míng on 2021-02-10.
// Copyright (c) 2021 Míng <i+ExCodable@iwill.im>. Released under the MIT license.
//
import Foundation
/// # 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.
@propertyWrapper
public final class ExCodable<Value: Codable> {
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)
}
public convenience init(wrappedValue initialValue: Value, _ stringKey: String? = nil, nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) {
self.init(wrappedValue: initialValue, stringKeys: stringKey.map { [$0] }, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode)
}
public convenience init(wrappedValue initialValue: Value, _ stringKeys: String..., nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) {
self.init(wrappedValue: initialValue, stringKeys: stringKeys, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode)
}
public convenience init(wrappedValue initialValue: Value, _ codingKeys: CodingKey..., nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)? = nil, decode: ((_ decoder: Decoder) throws -> Value?)? = nil) {
self.init(wrappedValue: initialValue, stringKeys: codingKeys.map { $0.stringValue }, nonnull: nonnull, throws: `throws`, encode: encode, decode: decode)
}
}
extension ExCodable 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)
}
}
extension ExCodable: Equatable where Value: Equatable {
public static func == (lhs: ExCodable<Value>, rhs: ExCodable<Value>) -> 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))" }
}
fileprivate protocol ExCodablePropertyWrapper {
func encode<Label: StringProtocol>(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws
func decode<Label: StringProtocol>(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool, converter: (any ExCodableDecodingTypeConverter.Type)?) throws
}
extension ExCodable: ExCodablePropertyWrapper {
fileprivate func encode<Label: StringProtocol>(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)
}
else {
try encoder.encode(wrappedValue, for: stringKeys?.first ?? String(label), nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`)
}
}
}
fileprivate func decode<Label: StringProtocol>(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)
}
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: - Encoder & Decoder
public extension Encoder { // , nonnull nonnull: Bool = false, throws throws: Bool = false
subscript<T: Encodable>(stringKey: String) -> T? { get { return nil }
nonmutating set { encode(newValue, for: stringKey) }
}
subscript<T: Encodable, K: CodingKey>(codingKey: K) -> T? { get { return nil }
nonmutating set { encode(newValue, for: codingKey) }
}
}
public extension Decoder { // , nonnull nonnull: Bool = false, throws throws: Bool = false
subscript<T: Decodable>(stringKeys: [String], converter converter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? {
return decode(stringKeys, as: T.self, converter: converter)
}
subscript<T: Decodable>(stringKeys: String ..., converter converter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? {
return decode(stringKeys, as: T.self, converter: converter)
}
subscript<T: Decodable, K: CodingKey>(codingKeys: [K], converter converter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? {
return decode(codingKeys, as: T.self, converter: converter)
}
subscript<T: Decodable, K: CodingKey>(codingKeys: K ..., converter converter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? {
return decode(codingKeys, as: T.self, converter: converter)
}
}
public extension Encoder {
func encodeNonnullThrows<T: Encodable>(_ value: T, for stringKey: String) throws {
try encode(value, for: stringKey, nonnull: true, throws: true)
}
func encodeThrows<T: Encodable>(_ value: T?, for stringKey: String) throws {
try encode(value, for: stringKey, nonnull: false, throws: true)
}
func encode<T: Encodable>(_ value: T?, for stringKey: String) {
try? encode(value, for: stringKey, nonnull: false, throws: false)
}
// TODO: internal -> fileprivate
internal func encode<T: Encodable>(_ value: T?, for stringKey: String, nonnull: Bool = false, throws: Bool = false) throws {
let dot: Character = "."
guard stringKey.contains(dot), stringKey.count > 1 else {
try encode(value, for: ExCodingKey(stringKey), nonnull: nonnull, throws: `throws`)
return
}
let keys = stringKey.split(separator: dot).map { ExCodingKey($0) }
var container = self.container(keyedBy: ExCodingKey.self)
for key in keys.dropLast() {
container = container.nestedContainer(keyedBy: ExCodingKey.self, forKey: key)
}
let codingKey = keys.last!
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)
}
}
func encodeNonnullThrows<T: Encodable, K: CodingKey>(_ value: T, for codingKey: K) throws {
try encode(value, for: codingKey, nonnull: true, throws: true)
}
func encodeThrows<T: Encodable, K: CodingKey>(_ value: T?, for codingKey: K) throws {
try encode(value, for: codingKey, nonnull: false, throws: true)
}
func encode<T: Encodable, K: CodingKey>(_ value: T?, for codingKey: K) {
try? encode(value, for: codingKey, nonnull: false, throws: false)
}
// TODO: internal -> fileprivate
internal func encode<T: Encodable, K: CodingKey>(_ value: T?, for codingKey: K, nonnull: Bool = false, throws: Bool = false) throws {
var container = self.container(keyedBy: K.self)
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)
}
}
}
public extension Decoder {
func decodeNonnullThrows<T: Decodable>(_ stringKeys: String ..., as type: T.Type = T.self, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T {
return try decodeNonnullThrows(stringKeys, as: type, converter: converter)
}
func decodeNonnullThrows<T: Decodable>(_ 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<T: Decodable>(_ stringKeys: String ..., as type: T.Type = T.self, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
return try decodeThrows(stringKeys, as: type, converter: converter)
}
func decodeThrows<T: Decodable>(_ 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<T: Decodable>(_ stringKeys: String ..., as type: T.Type = T.self, converter: (any ExCodableDecodingTypeConverter.Type)?) -> T? {
return decode(stringKeys, as: type, converter: converter)
}
func decode<T: Decodable>(_ 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)
}
// TODO: internal -> fileprivate
internal func decode<T: Decodable>(_ 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<T: Decodable, K: CodingKey>(_ codingKeys: K ..., as type: T.Type = T.self, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T {
return try decodeNonnullThrows(codingKeys, as: type, converter: converter)
}
func decodeNonnullThrows<T: Decodable, K: CodingKey>(_ 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<T: Decodable, K: CodingKey>(_ codingKeys: K ..., as type: T.Type = T.self, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
return try decodeThrows(codingKeys, as: type, converter: converter)
}
func decodeThrows<T: Decodable, K: CodingKey>(_ 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<T: Decodable, K: CodingKey>(_ codingKeys: K ..., as type: T.Type = T.self, converter: (any ExCodableDecodingTypeConverter.Type)?) -> T? {
return decode(codingKeys, as: type, converter: converter)
}
func decode<T: Decodable, K: CodingKey>(_ 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)
}
// TODO: internal -> fileprivate
internal func decode<T: Decodable, K: CodingKey>(_ 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)
}
return nil
}
}
// MARK: - ExCodingKey
fileprivate struct ExCodingKey {
public let stringValue: String, intValue: Int?
init<S: LosslessStringConvertible>(_ 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.init(intValue) }
}
// MARK: - KeyedDecodingContainer - alternative-keys + nested-keys + type-conversions
fileprivate extension KeyedDecodingContainer {
func decodeForAlternativeKeys<T: Decodable>(_ codingKeys: [Self.Key], as type: T.Type = T.self, nonnull: Bool, throws: Bool, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
var caughtError: Error?
do {
let codingKey = codingKeys.first!
if let value = try decodeForNestedKeys(codingKey, as: type, nonnull: nonnull, throws: `throws`, converter: converter) {
return value
}
}
catch { caughtError = error }
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 let caughtError { throw caughtError }
return nil
}
func decodeForNestedKeys<T: Decodable>(_ codingKey: Self.Key, as type: T.Type = T.self, nonnull: Bool, throws: Bool, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
var caughtError: Error?
do {
if let value = try decodeForValue(codingKey, as: type, nonnull: nonnull, throws: `throws`, converter: converter) {
return value
}
}
catch { caughtError = error }
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 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.self, forKey: key as! Self.Key)
if container == nil { return nil }
}
return container
}
func decodeForValue<T: Decodable>(_ codingKey: Self.Key, as type: T.Type = T.self, nonnull: Bool, throws: Bool, converter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
var caughtError: Error?
do {
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 { caughtError = error }
if contains(codingKey),
let value = decodeForTypeConversion(codingKey, as: type, converter: converter) {
return value
}
if let caughtError { throw caughtError }
return nil
}
func decodeForTypeConversion<T: Decodable>(_ 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 || wrappedType is Bool.Type {
if let int = try? decodeIfPresent(Int.self, forKey: codingKey) {
return (int != 0) as? T
}
else if let string = try? decodeIfPresent(String.self, forKey: codingKey) {
switch string.lowercased() {
case "true", "t", "yes", "y":
return true as? T
case "false", "f", "no", "n", "":
return false as? T
default:
if let int = Int(string) { return (int != 0) as? T }
else if let double = Double(string) { return (Int(double) != 0) as? T }
}
}
}
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 || 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 || 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 || 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 || 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 || 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 || 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 || 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 || 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 || 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 || 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 || 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 || 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
}
#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
}
// 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
}
return nil
}
}
public protocol ExCodableDecodingTypeConverter {
static func decode<T: Decodable, K: CodingKey>(_ container: KeyedDecodingContainer<K>, codingKey: K, as type: T.Type) -> T?
}
public struct ExCodableGlobalDecodingTypeConverter {}
// MARK: - Encodable & Decodable - external
// Methods defined in JSON&PList Encoder&Decoder
public protocol DataEncoder {
func encode<T: Encodable>(_ value: T) throws -> Data
}
public protocol DataDecoder {
func decode<T: Decodable>(_ type: T.Type, from data: Data) throws -> T
}
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 {
func encoded(using encoder: DataEncoder = JSONEncoder()) throws -> Data {
return try encoder.encode(self)
}
func encoded(using encoder: JSONEncoder = JSONEncoder()) throws -> [String: Any] {
let data = try encoded(using: encoder) as Data
return try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as! [String: Any]
}
func encoded(using encoder: JSONEncoder = JSONEncoder()) throws -> [Any] {
let data = try encoded(using: encoder) as Data
return try JSONSerialization.jsonObject(with: data, options: .fragmentsAllowed) as! [Any]
}
func encoded(using encoder: JSONEncoder = JSONEncoder()) throws -> String {
let data = try encoded(using: encoder) as Data
return String(data: data, encoding: .utf8)!
}
}
// Decodable.decode(Data) -> Decodable?
public extension Decodable {
static func decoded(from data: Data, using decoder: DataDecoder = JSONDecoder(), as type: Self.Type = Self.self) throws -> Self {
return try decoder.decode(type, from: data)
}
static func decoded(from json: [String: Any], using decoder: JSONDecoder = JSONDecoder(), as type: Self.Type = Self.self) throws -> Self {
let data = try JSONSerialization.data(withJSONObject: json, options: .fragmentsAllowed)
return try decoder.decode(type, from: data)
}
static func decoded(from jsonArray: [Any], using decoder: JSONDecoder = JSONDecoder(), as type: Self.Type = Self.self) throws -> Self {
let data = try JSONSerialization.data(withJSONObject: jsonArray, options: .fragmentsAllowed)
return try decoder.decode(type, from: data)
}
static func decoded(from string: String, using decoder: JSONDecoder = JSONDecoder(), as type: Self.Type = Self.self) throws -> Self {
let data = Data(string.utf8)
return try decoder.decode(type, from: data)
}
}
// Data.decode() -> Decodable?
public extension Data {
func decoded<T: Decodable>(using decoder: DataDecoder = JSONDecoder(), as type: T.Type = T.self) throws -> T {
return try decoder.decode(type, from: self)
}
}
public extension Dictionary {
func decoded<T: Decodable>(using decoder: JSONDecoder = JSONDecoder(), as type: T.Type = T.self) throws -> T {
let data = try JSONSerialization.data(withJSONObject: self, options: .fragmentsAllowed)
return try data.decoded(using: decoder, as: type)
}
}
public extension Array {
func decoded<T: Decodable>(using decoder: JSONDecoder = JSONDecoder(), as type: T.Type = T.self) throws -> T {
let data = try JSONSerialization.data(withJSONObject: self, options: .fragmentsAllowed)
return try data.decoded(using: decoder, as: type)
}
}
public extension String {
func decoded<T: Decodable>(using decoder: JSONDecoder = JSONDecoder(), as type: T.Type = T.self) throws -> T {
return try Data(self.utf8).decoded(using: decoder, as: type)
}
}
// MARK: - OptionalProtocol for Nested Optional
// - seealso: https://forums.swift.org/t/challenge-finding-base-type-of-nested-optionals/25096
public protocol OptionalProtocol {
static var wrappedType: Any.Type { get }
var wrapped: Any? { get }
}
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
}
}
}