-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathExCodable.swift
More file actions
633 lines (565 loc) · 36.3 KB
/
ExCodable.swift
File metadata and controls
633 lines (565 loc) · 36.3 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
//
// ExCodable.swift
// ExCodable
//
// Created by Míng on 2021-02-10.
// Copyright (c) 2023 Míng <i+ExCodable@iwill.im>. Released under the MIT license.
//
import Foundation
/**
* # ExCodable
*
* - `ExCodable`: A property-wrapper for mapping properties to JSON keys.
* - `ExAutoEncodable` & `ExAutoDecodable`: Protocols with default implementation for Encodable & Decodable.
* - `ExAutoCodable`: A typealias for `ExAutoEncodable & ExAutoDecodable`.
* - `Encodable` & `Decodable` extensions for encode/decode-ing from internal/external.
* - `Encoder` & `Encoder` extensions for encode/decode-ing properties one by one.
* - Supports Alternative-Keys, Nested-Keys, Type-Conversions and Default-Values.
*
* <#swift#> <#codable#> <#json#> <#model#> <#type-inference#>
* <#key-mapping#> <#property-wrapper#> <#coding-key#> <#subscript#>
* <#alternative-keys#> <#nested-keys#> <#type-conversions#>
*
* - seealso: [Usage](https://github.com/iwill/ExCodable#usage) from the `README.md`
* - seealso: `ExCodableTests.swift` from the `Tests`
* - seealso: [Decoding and overriding](https://www.swiftbysundell.com/articles/property-wrappers-in-swift/#decoding-and-overriding)
* and [Useful Codable extensions](https://www.swiftbysundell.com/tips/useful-codable-extensions/), by John Sundell.
*/
@propertyWrapper
public final class ExCodable<Value> {
fileprivate let stringKeys: [String]?
fileprivate let nonnull, `throws`: Bool?
fileprivate let encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)?, decode: ((_ decoder: Decoder) throws -> Value?)?
public var wrappedValue: Value
private init(wrappedValue initialValue: Value, stringKeys: [String]? = nil, nonnull: Bool? = nil, throws: Bool? = nil, encode: ((_ encoder: Encoder, _ value: Value) throws -> Void)?, decode: ((_ decoder: Decoder) throws -> Value?)?) {
(self.wrappedValue, self.stringKeys, self.nonnull, self.throws, self.encode, self.decode) = (initialValue, stringKeys, nonnull, `throws`, encode, decode)
}
public convenience init(wrappedValue 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: 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 EncodablePropertyWrapper {
func encode<Label: StringProtocol>(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws
}
extension ExCodable: EncodablePropertyWrapper where Value: Encodable {
fileprivate func encode<Label: StringProtocol>(to encoder: Encoder, label: Label, nonnull: Bool, throws: Bool) throws {
if encode != nil { try encode!(encoder, wrappedValue) }
else {
let value = deepUnwrap(wrappedValue)
if value != nil || self.nonnull ?? nonnull {
try encoder.encode(wrappedValue, for: stringKeys?.first ?? String(label), nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`)
}
}
}
}
fileprivate protocol DecodablePropertyWrapper {
func decode<Label: StringProtocol>(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws
}
extension ExCodable: DecodablePropertyWrapper where Value: Decodable {
fileprivate func decode<Label: StringProtocol>(from decoder: Decoder, label: Label, nonnull: Bool, throws: Bool, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws {
if let value = (decode != nil
? try decode!(decoder)
: try decoder.decode(stringKeys ?? [String(label)], nonnull: self.nonnull ?? nonnull, throws: self.throws ?? `throws`, typeConverter: typeConverter)) {
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 - internal
public extension Encodable {
func encode(to encoder: Encoder, nonnull: Bool, throws: Bool) throws {
var mirror: Mirror! = Mirror(reflecting: self)
while mirror != nil {
for child in mirror.children where child.label != nil {
try (child.value as? EncodablePropertyWrapper)?.encode(to: encoder, label: child.label!.dropFirst(), nonnull: false, throws: false)
}
mirror = mirror.superclassMirror
}
}
}
public extension Decodable {
func decode(from decoder: Decoder, nonnull: Bool, throws: Bool) throws {
var mirror: Mirror! = Mirror(reflecting: self)
while mirror != nil {
for child in mirror.children where child.label != nil {
try (child.value as? DecodablePropertyWrapper)?.decode(from: decoder, label: child.label!.dropFirst(), nonnull: false, throws: false, typeConverter: Self.self as? ExCodableDecodingTypeConverter.Type)
}
mirror = mirror.superclassMirror
}
}
}
// MARK: - Encoder & Decoder
public extension Encoder { // , abortIfNull nonnull: Bool = false, abortOnError 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 { // , abortIfNull nonnull: Bool = false, abortOnError throws: Bool = false
subscript<T: Decodable>(stringKeys: [String], typeConverter typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? {
return decode(stringKeys, as: T.self, typeConverter: typeConverter)
}
subscript<T: Decodable>(stringKeys: String ..., typeConverter typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? {
return decode(stringKeys, as: T.self, typeConverter: typeConverter)
}
subscript<T: Decodable, K: CodingKey>(codingKeys: [K], typeConverter typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? {
return decode(codingKeys, as: T.self, typeConverter: typeConverter)
}
subscript<T: Decodable, K: CodingKey>(codingKeys: K ..., typeConverter typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) -> T? {
return decode(codingKeys, as: T.self, typeConverter: typeConverter)
}
}
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)
}
internal/* fileprivate */ 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!
do {
if nonnull { try container.encode(value, forKey: codingKey) }
else { try container.encodeIfPresent(value, forKey: codingKey) }
}
catch { if `throws` || nonnull { throw error } }
}
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)
}
internal/* fileprivate */ 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)
do {
if nonnull { try container.encode(value, forKey: codingKey) }
else { try container.encodeIfPresent(value, forKey: codingKey) }
}
catch { if `throws` || nonnull { throw error } }
}
}
public extension Decoder {
func decodeNonnullThrows<T: Decodable>(_ stringKeys: String ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T {
return try decodeNonnullThrows(stringKeys, as: type, typeConverter: typeConverter)
}
func decodeNonnullThrows<T: Decodable>(_ stringKeys: [String], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T {
return try decode(stringKeys, as: type, nonnull: true, throws: true, typeConverter: typeConverter)!
}
func decodeThrows<T: Decodable>(_ stringKeys: String ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
return try decodeThrows(stringKeys, as: type, typeConverter: typeConverter)
}
func decodeThrows<T: Decodable>(_ stringKeys: [String], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
return try decode(stringKeys, as: type, nonnull: false, throws: true, typeConverter: typeConverter)
}
func decode<T: Decodable>(_ stringKeys: String ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? {
return decode(stringKeys, as: type, typeConverter: typeConverter)
}
func decode<T: Decodable>(_ stringKeys: [String], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? {
return try? decode(stringKeys, as: type, nonnull: false, throws: false, typeConverter: typeConverter)
}
// TODO: DEPRECATED
internal func decode<T: Decodable>(_ stringKeys: [String], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) throws -> T? {
return try decode(stringKeys.map { ExCodingKey($0) }, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter)
}
// fileprivate func decode<T: Decodable>(_ stringKeys: [String], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
// return try decode(stringKeys.map { ExCodingKey($0) }, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter)
// }
func decodeNonnullThrows<T: Decodable, K: CodingKey>(_ codingKeys: K ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T {
return try decodeNonnullThrows(codingKeys, as: type, typeConverter: typeConverter)
}
func decodeNonnullThrows<T: Decodable, K: CodingKey>(_ codingKeys: [K], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T {
return try decode(codingKeys, as: type, nonnull: true, throws: true, typeConverter: typeConverter)!
}
func decodeThrows<T: Decodable, K: CodingKey>(_ codingKeys: K ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
return try decodeThrows(codingKeys, as: type, typeConverter: typeConverter)
}
func decodeThrows<T: Decodable, K: CodingKey>(_ codingKeys: [K], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
return try decode(codingKeys, as: type, nonnull: false, throws: true, typeConverter: typeConverter)
}
func decode<T: Decodable, K: CodingKey>(_ codingKeys: K ..., as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? {
return decode(codingKeys, as: type, typeConverter: typeConverter)
}
func decode<T: Decodable, K: CodingKey>(_ codingKeys: [K], as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? {
return try? decode(codingKeys, as: type, nonnull: false, throws: false, typeConverter: typeConverter)
}
// TODO: DEPRECATED
internal func decode<T: Decodable, K: CodingKey>(_ codingKeys: [K], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, typeConverter: (any ExCodableDecodingTypeConverter.Type)? = nil) throws -> T? {
do {
let container = try self.container(keyedBy: K.self)
return try container.decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter)
}
catch { if `throws` || nonnull { throw error } }
return nil
}
// fileprivate func decode<T: Decodable, K: CodingKey>(_ codingKeys: [K], as type: T.Type = T.self, nonnull: Bool = false, throws: Bool = false, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
// do {
// let container = try self.container(keyedBy: K.self)
// return try container.decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter)
// }
// catch { if `throws` || nonnull { throw error } }
// return nil
// }
}
// MARK: - ExCodingKey
private 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 {
public init?(stringValue: String) { self.init(stringValue) }
public 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, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
var firstError: Error?
do {
let codingKey = codingKeys.first!
if let value = try decodeForNestedKeys(codingKey, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) {
return value
}
}
catch { firstError = error }
let codingKeys = Array(codingKeys.dropFirst())
if !codingKeys.isEmpty,
let value = try? decodeForAlternativeKeys(codingKeys, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) {
return value
}
if (`throws` || nonnull) && firstError != nil { throw firstError! }
return nil
}
func decodeForNestedKeys<T: Decodable>(_ codingKey: Self.Key, as type: T.Type = T.self, nonnull: Bool, throws: Bool, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
var firstError: Error?
do {
if let value = try decodeForValue(codingKey, as: type, nonnull: nonnull, throws: `throws`, typeConverter: typeConverter) {
return value
}
}
catch { firstError = 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`, typeConverter: typeConverter) {
return value
}
}
if firstError != nil && (`throws` || nonnull) { throw firstError! }
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, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) throws -> T? {
var firstError: Error?
do {
if let value = (nonnull
? (`throws` ? try decode(type, forKey: codingKey) : try? decode(type, forKey: codingKey))
: (`throws` ? try decodeIfPresent(type, forKey: codingKey) : try? decodeIfPresent(type, forKey: codingKey))) {
return value
}
}
catch { firstError = error }
if contains(codingKey) {
if let value = decodeForTypeConversion(codingKey, as: type, typeConverter: typeConverter) {
return value
}
if #available(iOS 16.0.0, *) {
// TODO: how to fix "Type 'any Decodable' cannot conform to 'Decodable'"
// if let rawType = type as? any (Decodable&RawRepresentable<Decodable>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< Bool >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< Int >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< Int8 >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< Int16>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< Int32>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< Int64>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< UInt >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< UInt8 >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< UInt16>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< UInt32>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable< UInt64>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable<Double >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable<Float >).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable<Float16>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable<Float32>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable<Float64>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
// if let rawType = type as? any (Decodable&RawRepresentable<Float80>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
// if let rawType = type as? any (Decodable&RawRepresentable<Float96>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
if let rawType = type as? any (Decodable&RawRepresentable<String>).Type { return decodeForRawRepresentable(codingKey, as: rawType, typeConverter: typeConverter) as? T }
}
}
if firstError != nil && (`throws` || nonnull) { throw firstError! }
return nil
}
// TODO: how to fix "Type 'any Decodable' cannot conform to 'Decodable'"
// func decodeForRawRepresentable<T: Decodable&RawRepresentable<Decodable>>(_ codingKey: Self.Key, as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? {
// if let rawValue = decodeForTypeConversion(codingKey, as: T.RawValue.self, typeConverter: typeConverter) {
// return type.init(rawValue: rawValue)
// }
// return nil
// }
func decodeForRawRepresentable<T: Decodable>(_ codingKey: Self.Key, as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? where T: RawRepresentable, T.RawValue: Decodable {
if let rawValue = decodeForTypeConversion(codingKey, as: T.RawValue.self, typeConverter: typeConverter) {
return type.init(rawValue: rawValue)
}
return nil
}
func decodeForTypeConversion<T: Decodable>(_ codingKey: Self.Key, as type: T.Type = T.self, typeConverter: (any ExCodableDecodingTypeConverter.Type)?) -> T? {
if type is Bool.Type {
if let int = try? decodeIfPresent(Int.self, forKey: codingKey) {
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 {
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 {
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 {
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 {
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 {
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 {
if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt(bool ? 1 : 0) as? T }
else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt(string) { return value as? T }
}
else if type is UInt8.Type {
if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt8(bool ? 1 : 0) as? T }
else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt8(string) { return value as? T }
}
else if type is UInt16.Type {
if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt16(bool ? 1 : 0) as? T }
else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt16(string) { return value as? T }
}
else if type is UInt32.Type {
if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt32(bool ? 1 : 0) as? T }
else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt32(string) { return value as? T }
}
else if type is UInt64.Type {
if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return UInt64(bool ? 1 : 0) as? T }
else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = UInt64(string) { return value as? T }
}
else if type 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 {
if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float(int64) as? T } // include all Int types
else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float(string) { return value as? T }
}
else if type is String.Type {
if let bool = try? decodeIfPresent(Bool.self, forKey: codingKey) { return String(describing: bool) as? T }
else if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return String(describing: int64) as? T } // include all Int types
else if let double = try? decodeIfPresent(Double.self, forKey: codingKey) { return String(describing: double) as? T } // include Float
}
if #available(iOS 14.0, *) {
if type is Float16.Type {
if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float16(int64) as? T } // include all Int types
else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float16(string) { return value as? T }
}
else if type is Float32.Type {
if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float32(int64) as? T } // include all Int types
else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float32(string) { return value as? T }
}
else if type is Float64.Type {
if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float64(int64) as? T } // include all Int types
else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float64(string) { return value as? T }
}
// else if type is Float80.Type {
// if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float80(int64) as? T } // include all Int types
// else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float80(string) { return value as? T }
// }
// else if type is Float96.Type {
// if let int64 = try? decodeIfPresent(Int64.self, forKey: codingKey) { return Float96(int64) as? T } // include all Int types
// else if let string = try? decodeIfPresent(String.self, forKey: codingKey), let value = Float96(string) { return value as? T }
// }
}
// specific converter for type `T`, via `extension T: ExCodableDecodingTypeConverter`
if let typeConverter,
let value = try? typeConverter.decode(self, codingKey: codingKey, as: type) {
return value
}
// global converter for all types, via `extension KeyedDecodingContainer: ExCodableDecodingTypeConverter`
if let selfConverter = Self.self as? ExCodableDecodingTypeConverter.Type,
let value = try? selfConverter.decode(self, codingKey: codingKey, as: type) {
return value
}
return nil
}
}
public protocol ExCodableDecodingTypeConverter {
static func decode<T: Decodable, K: CodingKey>(_ container: KeyedDecodingContainer<K>, codingKey: K, as type: T.Type) throws -> T?
}
// MARK: - Encodable & Decodable - external
// 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)
}
}
// Methods from 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 {}
// MARK: Optional
private protocol OptionalProtocol {
var deepWrapped: Any? { get }
}
extension Optional: OptionalProtocol {
var deepWrapped: Any? {
guard case let .some(wrapped) = self else { return nil }
guard let wrapped = wrapped as? OptionalProtocol else { return wrapped }
return wrapped.deepWrapped
}
}
private func deepUnwrap(_ any: Any) -> Any? {
if let any = any as? OptionalProtocol {
return any.deepWrapped
}
return any
}