-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathAnyCodable.swift
More file actions
80 lines (75 loc) · 2.46 KB
/
Copy pathAnyCodable.swift
File metadata and controls
80 lines (75 loc) · 2.46 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
//
// AnyCodable.swift
//
//
// Created by Anton Begehr on 2025-07-10.
//
import Foundation
public enum AnyCodable: Codable {
case string(String)
case int(Int)
case double(Double)
case bool(Bool)
case array([AnyCodable])
case dictionary([String: AnyCodable])
case null
public init(_ value: Any?) {
switch value {
case let string as String:
self = .string(string)
case let int as Int:
self = .int(int)
case let double as Double:
self = .double(double)
case let bool as Bool:
self = .bool(bool)
case let array as [Any]:
self = .array(array.map { AnyCodable($0) })
case let dict as [String: Any]:
self = .dictionary(dict.mapValues { AnyCodable($0) })
case nil:
self = .null
default:
self = .null // Fallback for unsupported types
}
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self = .null
} else if let string = try? container.decode(String.self) {
self = .string(string)
} else if let int = try? container.decode(Int.self) {
self = .int(int)
} else if let double = try? container.decode(Double.self) {
self = .double(double)
} else if let bool = try? container.decode(Bool.self) {
self = .bool(bool)
} else if let array = try? container.decode([AnyCodable].self) {
self = .array(array)
} else if let dict = try? container.decode([String: AnyCodable].self) {
self = .dictionary(dict)
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unsupported JSON type")
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .string(let value):
try container.encode(value)
case .int(let value):
try container.encode(value)
case .double(let value):
try container.encode(value)
case .bool(let value):
try container.encode(value)
case .array(let value):
try container.encode(value)
case .dictionary(let value):
try container.encode(value)
case .null:
try container.encodeNil()
}
}
}