forked from LoopKit/LoopKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnyCodableEquatable.swift
More file actions
46 lines (39 loc) · 1.27 KB
/
AnyCodableEquatable.swift
File metadata and controls
46 lines (39 loc) · 1.27 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
//
// AnyCodableEquatable.swift
// LoopKit
//
// Created by Darin Krauss on 2/8/22.
// Copyright © 2022 LoopKit Authors. All rights reserved.
//
import Foundation
public struct AnyCodableEquatable: Codable, Equatable {
public enum Error: Swift.Error {
case unknownType
}
public let wrapped: Any
private let equals: (Self) -> Bool
public init<T: Codable & Equatable>(_ wrapped: T) {
self.wrapped = wrapped
self.equals = { $0.wrapped as? T == wrapped }
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(String.self) {
self.init(value)
} else if let value = try? container.decode(Int.self) {
self.init(value)
} else if let value = try? container.decode(Double.self) {
self.init(value)
} else if let value = try? container.decode(Bool.self) {
self.init(value)
} else {
throw Error.unknownType
}
}
public func encode(to encoder: Encoder) throws {
try (wrapped as? Encodable)?.encode(to: encoder)
}
public static func ==(lhs: AnyCodableEquatable, rhs: AnyCodableEquatable) -> Bool {
return lhs.equals(rhs)
}
}