-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathCustomPersistable.swift
261 lines (239 loc) · 9.54 KB
/
CustomPersistable.swift
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
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
// MARK: Public API
/**
A type which can be mapped to and from a type which Realm supports.
To store types in a Realm which Realm doesn't natively support, declare the
type as conforming to either CustomPersistable or FailableCustomPersistable.
This requires defining an associatedtype named `PersistedType` which indicates
what Realm type this type will be mapped to, an initializer taking the
`PersistedType`, and a property which returns the appropriate `PersistedType`.
For example, to make `URL` persistable:
```
// Not all strings are valid URLs, so this uses
// FailableCustomPersistable to handle the case when the data
// in the Realm isn't a valid URL.
extension URL: FailableCustomPersistable {
typealias PersistedType = String
init?(persistedValue: String) {
self.init(string: persistedValue)
}
var persistableValue: PersistedType {
self.absoluteString
}
}
```
After doing this, you can define properties using URL:
```
class MyModel: Object {
@Persisted var url: URL
@Persisted var mapOfUrls: Map<String, URL>
}
```
`PersistedType` can be any of the primitive types supported by Realm or an
`EmbeddedObject` subclass. `EmbeddedObject` subclasses can be used if you
need to store more than one piece of data for your mapped type. For
example, to store `CGPoint`:
```
// Define the storage object. A type used for custom mappings
// does not have to be used exclusively for custom mappings,
// and more than one type can map to a single embedded object
// type.
class CGPointObject: EmbeddedObject {
@Persisted var double: x
@Persisted var double: y
}
// Define the mapping. This mapping isn't failable, as the
// data stored in the Realm can always be interpreted as a
// CGPoint.
extension CGPoint: CustomPersistable {
typealias PersistedType = CGPointObject
init(persistedValue: CGPointObject) {
self.init(x: persistedValue.x, y: persistedValue.y)
}
var persistableValue: PersistedType {
CGPointObject(value: [x, y])
}
}
class PointModel: Object {
// Note that types which are mapped to embedded objects do
// not have to be optional (but can be).
@Persisted var point: CGPoint
@Persisted var line: List<CGPoint>
}
```
Queries are performed on the persisted type and not the custom persistable
type. Values passed into queries can be of either the persisted type or
custom persistable type. For custom persistable types which map to embedded
objects, memberwise equality will be used. For examples,
`realm.objects(PointModel.self).where { $0.point == CGPoint(x: 1, y: 2) }`
is equivalent to `"point.x == 1 AND point.y == 2"`.
*/
public protocol CustomPersistable: _CustomPersistable {
/// Construct an instance of this type from the persisted type.
init(persistedValue: PersistedType)
/// Construct an instance of the persisted type from this type.
var persistableValue: PersistedType { get }
}
/**
A type which can be mapped to and from a type which Realm supports.
This protocol is identical to `CustomPersistable`, except with
`init?(persistedValue:)` instead of `init(persistedValue:)`.
FailableCustomPersistable types are force-unwrapped in
non-Optional contexts, and collapsed to `nil` in Optional contexts.
That is, if you have a value that can't be converted to a URL, reading a
`@Persisted var url: URL` property will throw an unwrapped failed exception, and
reading from `Persisted var url: URL?` will return `nil`.
*/
public protocol FailableCustomPersistable: _CustomPersistable {
/// Construct an instance of the this type from the persisted type,
/// returning nil if the conversion is not possible.
///
/// This function must not return `nil` when given a default-initalized
/// `PersistedType()`.
init?(persistedValue: PersistedType)
/// Construct an instance of the persisted type from this type.
var persistableValue: PersistedType { get }
}
// MARK: - Implementation
/// :nodoc:
public protocol _CustomPersistable: _PersistableInsideOptional, _RealmCollectionValueInsideOptional {}
/// :nodoc:
extension _CustomPersistable { // _RealmSchemaDiscoverable
/// :nodoc:
public static var _rlmType: PropertyType { PersistedType._rlmType }
/// :nodoc:
public static var _rlmOptional: Bool { PersistedType._rlmOptional }
/// :nodoc:
public static var _rlmRequireObjc: Bool { false }
/// :nodoc:
public func _rlmPopulateProperty(_ prop: RLMProperty) { }
/// :nodoc:
public static func _rlmPopulateProperty(_ prop: RLMProperty) {
prop.customMappingIsOptional = prop.optional
if prop.type == .object && (!prop.collection || prop.dictionary) {
prop.optional = true
}
PersistedType._rlmPopulateProperty(prop)
}
}
extension CustomPersistable { // _Persistable
/// :nodoc:
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Self {
return Self(persistedValue: PersistedType._rlmGetProperty(obj, key))
}
/// :nodoc:
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Self? {
return PersistedType._rlmGetPropertyOptional(obj, key).flatMap(Self.init)
}
/// :nodoc:
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Self) {
PersistedType._rlmSetProperty(obj, key, value.persistableValue)
}
/// :nodoc:
public static func _rlmSetAccessor(_ prop: RLMProperty) {
if prop.customMappingIsOptional {
prop.swiftAccessor = BridgedPersistedPropertyAccessor<Optional<Self>>.self
} else if prop.optional {
prop.swiftAccessor = CustomPersistablePropertyAccessor<Self>.self
} else {
prop.swiftAccessor = BridgedPersistedPropertyAccessor<Self>.self
}
}
/// :nodoc:
public static func _rlmDefaultValue() -> Self {
Self(persistedValue: PersistedType._rlmDefaultValue())
}
/// :nodoc:
public func hash(into hasher: inout Hasher) {
persistableValue.hash(into: &hasher)
}
}
extension FailableCustomPersistable { // _Persistable
/// :nodoc:
public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Self {
let persistedValue = PersistedType._rlmGetProperty(obj, key)
if let value = Self(persistedValue: persistedValue) {
return value
}
throwRealmException("Failed to convert persisted value '\(persistedValue)' to type '\(Self.self)' in a non-optional context.")
}
/// :nodoc:
public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Self? {
return PersistedType._rlmGetPropertyOptional(obj, key).flatMap(Self.init)
}
/// :nodoc:
public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Self) {
PersistedType._rlmSetProperty(obj, key, value.persistableValue)
}
/// :nodoc:
public static func _rlmSetAccessor(_ prop: RLMProperty) {
if prop.customMappingIsOptional {
prop.swiftAccessor = BridgedPersistedPropertyAccessor<Optional<Self>>.self
} else if prop.optional {
prop.swiftAccessor = CustomPersistablePropertyAccessor<Self>.self
} else {
prop.swiftAccessor = BridgedPersistedPropertyAccessor<Self>.self
}
}
/// :nodoc:
public static func _rlmDefaultValue() -> Self {
if let value = Self(persistedValue: PersistedType._rlmDefaultValue()) {
return value
}
throwRealmException("Failed to default construct a \(Self.self) using the default value for persisted type \(PersistedType.self). " +
"This conversion must either succeed, the property must be optional, or you must explicitly specify a default value for the property.")
}
/// :nodoc:
public func hash(into hasher: inout Hasher) {
persistableValue.hash(into: &hasher)
}
}
extension CustomPersistable { // _ObjcBridgeable
/// :nodoc:
public static func _rlmFromObjc(_ value: Any, insideOptional: Bool) -> Self? {
if let value = PersistedType._rlmFromObjc(value) {
return Self(persistedValue: value)
}
if let value = value as? Self {
return value
}
if !insideOptional && value is NSNull {
return Self._rlmDefaultValue()
}
return nil
}
/// :nodoc:
public var _rlmObjcValue: Any { persistableValue }
}
extension FailableCustomPersistable { // _ObjcBridgeable
/// :nodoc:
public static func _rlmFromObjc(_ value: Any, insideOptional: Bool) -> Self? {
if let value = PersistedType._rlmFromObjc(value) {
return Self(persistedValue: value)
}
if let value = value as? Self {
return value
}
return nil
}
/// :nodoc:
public var _rlmObjcValue: Any { persistableValue }
}