|
3 | 3 | // Copyright © 2021-present Alexis Bridoux. |
4 | 4 | // MIT license, see LICENSE file for details |
5 | 5 |
|
| 6 | +import CoreData |
| 7 | + |
6 | 8 | /// A type that can be used in a predicate as a test value |
| 9 | +/// |
| 10 | +/// - Default implementations are provided to ensure formatting. |
| 11 | +/// - Implementation for `NSManagedObject` is provided (for the relationships) and will use the [`objectID`](https://developer.apple.com/documentation/coredata/nsmanagedobject/1506848-objectid) property |
7 | 12 | public protocol DatabaseTestValue { |
8 | 13 |
|
9 | 14 | /// Formatted string value that can be used in the format of a `NSPredicate` |
10 | 15 | var testValue: String { get } |
11 | 16 | } |
12 | 17 |
|
| 18 | +// MARK: - Scalar |
| 19 | + |
13 | 20 | extension String: DatabaseTestValue { |
14 | 21 |
|
15 | 22 | public var testValue: String { #""\#(self)""# } |
@@ -45,29 +52,46 @@ extension Float: DatabaseTestValue { |
45 | 52 | public var testValue: String { String(describing: self) } |
46 | 53 | } |
47 | 54 |
|
| 55 | +extension Bool: DatabaseTestValue { |
| 56 | + public var testValue: String { String(describing: self) } |
| 57 | +} |
| 58 | + |
| 59 | +// MARK: - Optional |
| 60 | + |
48 | 61 | extension Optional: DatabaseTestValue where Wrapped: DatabaseTestValue { |
49 | 62 |
|
50 | 63 | public var testValue: String { |
51 | 64 | switch self { |
52 | 65 | case .none: return "nil" |
53 | | - case .some(let wrapped): |
| 66 | + case let .some(wrapped): |
54 | 67 | return wrapped.testValue |
55 | 68 | } |
56 | 69 | } |
57 | 70 | } |
58 | 71 |
|
| 72 | +extension NSManagedObject: DatabaseTestValue { |
| 73 | + |
| 74 | + public var testValue: String { String(describing: objectID) } |
| 75 | +} |
| 76 | + |
| 77 | +// MARK: - Array |
| 78 | + |
59 | 79 | extension Array: DatabaseTestValue where Element: DatabaseTestValue { |
60 | 80 |
|
61 | 81 | public var testValue: String { |
62 | 82 | "{ \(map(\.testValue).joined(separator: ","))}" |
63 | 83 | } |
64 | 84 | } |
65 | 85 |
|
| 86 | +// MARK: - RawRepresentable |
| 87 | + |
66 | 88 | extension DatabaseTestValue where Self: RawRepresentable, RawValue: DatabaseValue { |
67 | 89 |
|
68 | 90 | public var testValue: String { String(describing: rawValue) } |
69 | 91 | } |
70 | 92 |
|
| 93 | +// MARK: - Range |
| 94 | + |
71 | 95 | extension ClosedRange: DatabaseTestValue where Bound: Numeric { |
72 | 96 |
|
73 | 97 | public var testValue: String { |
|
0 commit comments