-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathJSONDecoderExtesions.swift
More file actions
73 lines (66 loc) · 2.19 KB
/
JSONDecoderExtesions.swift
File metadata and controls
73 lines (66 loc) · 2.19 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
//
// JSONDecoderExtesions.swift
//
// Created by DoubleHH on 2018/2/2.
//
import Foundation
// MARK: - handle typeMismatch exceptions in JSONDecoder. You can expand the type of you want.
extension KeyedDecodingContainer {
public func decodeIfPresent(_ type: String.Type, forKey key: K) throws -> String? {
if let value = try? decode(type, forKey: key) {
return value
}
if let value = try? decode(Int.self, forKey: key) {
return String(value)
}
if let value = try? decode(Float.self, forKey: key) {
return String(value)
}
return nil
}
public func decodeIfPresent(_ type: Int.Type, forKey key: K) throws -> Int? {
if let value = try? decode(type, forKey: key) {
return value
}
if let value = try? decode(String.self, forKey: key) {
return Int(value)
}
return nil
}
public func decodeIfPresent(_ type: Float.Type, forKey key: K) throws -> Float? {
if let value = try? decode(type, forKey: key) {
return value
}
if let value = try? decode(String.self, forKey: key) {
return Float(value)
}
return nil
}
public func decodeIfPresent(_ type: Bool.Type, forKey key: K) throws -> Bool? {
if let value = try? decode(type, forKey: key) {
return value
}
if let value = try? decode(String.self, forKey: key) {
if let valueInt = Int(value) {
return Bool(valueInt != 0)
}
return nil
}
if let value = try? decode(Int.self, forKey: key) {
return Bool(value != 0)
}
return nil
}
public func decodeIfPresent(_ type: Double.Type, forKey key: K) throws -> Double? {
if let value = try? decode(type, forKey: key) {
return value
}
if let value = try? decode(String.self, forKey: key) {
return Double(value)
}
return nil
}
public func decodeIfPresent<T>(_ type: T.Type, forKey key: K) throws -> T? where T : Decodable {
return try? decode(type, forKey: key)
}
}