CustomPersistable.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2021 Realm Inc.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. //
  17. ////////////////////////////////////////////////////////////////////////////
  18. import Foundation
  19. import Realm
  20. // MARK: Public API
  21. /**
  22. A type which can be mapped to and from a type which Realm supports.
  23. To store types in a Realm which Realm doesn't natively support, declare the
  24. type as conforming to either CustomPersistable or FailableCustomPersistable.
  25. This requires defining an associatedtype named `PersistedType` which indicates
  26. what Realm type this type will be mapped to, an initializer taking the
  27. `PersistedType`, and a property which returns the appropriate `PersistedType`.
  28. For example, to make `URL` persistable:
  29. ```
  30. // Not all strings are valid URLs, so this uses
  31. // FailableCustomPersistable to handle the case when the data
  32. // in the Realm isn't a valid URL.
  33. extension URL: FailableCustomPersistable {
  34. typealias PersistedType = String
  35. init?(persistedValue: String) {
  36. self.init(string: persistedValue)
  37. }
  38. var persistableValue: PersistedType {
  39. self.absoluteString
  40. }
  41. }
  42. ```
  43. After doing this, you can define properties using URL:
  44. ```
  45. class MyModel: Object {
  46. @Persisted var url: URL
  47. @Persisted var mapOfUrls: Map<String, URL>
  48. }
  49. ```
  50. `PersistedType` can be any of the primitive types supported by Realm or an
  51. `EmbeddedObject` subclass. `EmbeddedObject` subclasses can be used if you
  52. need to store more than one piece of data for your mapped type. For
  53. example, to store `CGPoint`:
  54. ```
  55. // Define the storage object. A type used for custom mappings
  56. // does not have to be used exclusively for custom mappings,
  57. // and more than one type can map to a single embedded object
  58. // type.
  59. class CGPointObject: EmbeddedObject {
  60. @Persisted var double: x
  61. @Persisted var double: y
  62. }
  63. // Define the mapping. This mapping isn't failable, as the
  64. // data stored in the Realm can always be interpreted as a
  65. // CGPoint.
  66. extension CGPoint: CustomPersistable {
  67. typealias PersistedType = CGPointObject
  68. init(persistedValue: CGPointObject) {
  69. self.init(x: persistedValue.x, y: persistedValue.y)
  70. }
  71. var persistableValue: PersistedType {
  72. CGPointObject(value: [x, y])
  73. }
  74. }
  75. class PointModel: Object {
  76. // Note that types which are mapped to embedded objects do
  77. // not have to be optional (but can be).
  78. @Persisted var point: CGPoint
  79. @Persisted var line: List<CGPoint>
  80. }
  81. ```
  82. Queries are performed on the persisted type and not the custom persistable
  83. type. Values passed into queries can be of either the persisted type or
  84. custom persistable type. For custom persistable types which map to embedded
  85. objects, memberwise equality will be used. For examples,
  86. `realm.objects(PointModel.self).where { $0.point == CGPoint(x: 1, y: 2) }`
  87. is equivalent to `"point.x == 1 AND point.y == 2"`.
  88. */
  89. public protocol CustomPersistable: _CustomPersistable {
  90. /// Construct an instance of this type from the persisted type.
  91. init(persistedValue: PersistedType)
  92. /// Construct an instance of the persisted type from this type.
  93. var persistableValue: PersistedType { get }
  94. }
  95. /**
  96. A type which can be mapped to and from a type which Realm supports.
  97. This protocol is identical to `CustomPersistable`, except with
  98. `init?(persistedValue:)` instead of `init(persistedValue:)`.
  99. FailableCustomPersistable types are force-unwrapped in
  100. non-Optional contexts, and collapsed to `nil` in Optional contexts.
  101. That is, if you have a value that can't be converted to a URL, reading a
  102. `@Persisted var url: URL` property will throw an unwrapped failed exception, and
  103. reading from `Persisted var url: URL?` will return `nil`.
  104. */
  105. public protocol FailableCustomPersistable: _CustomPersistable {
  106. /// Construct an instance of the this type from the persisted type,
  107. /// returning nil if the conversion is not possible.
  108. ///
  109. /// This function must not return `nil` when given a default-initalized
  110. /// `PersistedType()`.
  111. init?(persistedValue: PersistedType)
  112. /// Construct an instance of the persisted type from this type.
  113. var persistableValue: PersistedType { get }
  114. }
  115. // MARK: - Implementation
  116. /// :nodoc:
  117. public protocol _CustomPersistable: _PersistableInsideOptional, _RealmCollectionValueInsideOptional {}
  118. /// :nodoc:
  119. extension _CustomPersistable { // _RealmSchemaDiscoverable
  120. /// :nodoc:
  121. public static var _rlmType: PropertyType { PersistedType._rlmType }
  122. /// :nodoc:
  123. public static var _rlmOptional: Bool { PersistedType._rlmOptional }
  124. /// :nodoc:
  125. public static var _rlmRequireObjc: Bool { false }
  126. /// :nodoc:
  127. public func _rlmPopulateProperty(_ prop: RLMProperty) { }
  128. /// :nodoc:
  129. public static func _rlmPopulateProperty(_ prop: RLMProperty) {
  130. prop.customMappingIsOptional = prop.optional
  131. if prop.type == .object && (!prop.collection || prop.dictionary) {
  132. prop.optional = true
  133. }
  134. PersistedType._rlmPopulateProperty(prop)
  135. }
  136. }
  137. extension CustomPersistable { // _Persistable
  138. /// :nodoc:
  139. public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Self {
  140. return Self(persistedValue: PersistedType._rlmGetProperty(obj, key))
  141. }
  142. /// :nodoc:
  143. public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Self? {
  144. return PersistedType._rlmGetPropertyOptional(obj, key).flatMap(Self.init)
  145. }
  146. /// :nodoc:
  147. public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Self) {
  148. PersistedType._rlmSetProperty(obj, key, value.persistableValue)
  149. }
  150. /// :nodoc:
  151. public static func _rlmSetAccessor(_ prop: RLMProperty) {
  152. if prop.customMappingIsOptional {
  153. prop.swiftAccessor = BridgedPersistedPropertyAccessor<Optional<Self>>.self
  154. } else if prop.optional {
  155. prop.swiftAccessor = CustomPersistablePropertyAccessor<Self>.self
  156. } else {
  157. prop.swiftAccessor = BridgedPersistedPropertyAccessor<Self>.self
  158. }
  159. }
  160. /// :nodoc:
  161. public static func _rlmDefaultValue() -> Self {
  162. Self(persistedValue: PersistedType._rlmDefaultValue())
  163. }
  164. /// :nodoc:
  165. public func hash(into hasher: inout Hasher) {
  166. persistableValue.hash(into: &hasher)
  167. }
  168. }
  169. extension FailableCustomPersistable { // _Persistable
  170. /// :nodoc:
  171. public static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Self {
  172. let persistedValue = PersistedType._rlmGetProperty(obj, key)
  173. if let value = Self(persistedValue: persistedValue) {
  174. return value
  175. }
  176. throwRealmException("Failed to convert persisted value '\(persistedValue)' to type '\(Self.self)' in a non-optional context.")
  177. }
  178. /// :nodoc:
  179. public static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Self? {
  180. return PersistedType._rlmGetPropertyOptional(obj, key).flatMap(Self.init)
  181. }
  182. /// :nodoc:
  183. public static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Self) {
  184. PersistedType._rlmSetProperty(obj, key, value.persistableValue)
  185. }
  186. /// :nodoc:
  187. public static func _rlmSetAccessor(_ prop: RLMProperty) {
  188. if prop.customMappingIsOptional {
  189. prop.swiftAccessor = BridgedPersistedPropertyAccessor<Optional<Self>>.self
  190. } else if prop.optional {
  191. prop.swiftAccessor = CustomPersistablePropertyAccessor<Self>.self
  192. } else {
  193. prop.swiftAccessor = BridgedPersistedPropertyAccessor<Self>.self
  194. }
  195. }
  196. /// :nodoc:
  197. public static func _rlmDefaultValue() -> Self {
  198. if let value = Self(persistedValue: PersistedType._rlmDefaultValue()) {
  199. return value
  200. }
  201. throwRealmException("Failed to default construct a \(Self.self) using the default value for persisted type \(PersistedType.self). " +
  202. "This conversion must either succeed, the property must be optional, or you must explicitly specify a default value for the property.")
  203. }
  204. /// :nodoc:
  205. public func hash(into hasher: inout Hasher) {
  206. persistableValue.hash(into: &hasher)
  207. }
  208. }
  209. extension CustomPersistable { // _ObjcBridgeable
  210. /// :nodoc:
  211. public static func _rlmFromObjc(_ value: Any, insideOptional: Bool) -> Self? {
  212. if let value = PersistedType._rlmFromObjc(value) {
  213. return Self(persistedValue: value)
  214. }
  215. if let value = value as? Self {
  216. return value
  217. }
  218. if !insideOptional && value is NSNull {
  219. return Self._rlmDefaultValue()
  220. }
  221. return nil
  222. }
  223. /// :nodoc:
  224. public var _rlmObjcValue: Any { persistableValue }
  225. }
  226. extension FailableCustomPersistable { // _ObjcBridgeable
  227. /// :nodoc:
  228. public static func _rlmFromObjc(_ value: Any, insideOptional: Bool) -> Self? {
  229. if let value = PersistedType._rlmFromObjc(value) {
  230. return Self(persistedValue: value)
  231. }
  232. if let value = value as? Self {
  233. return value
  234. }
  235. return nil
  236. }
  237. /// :nodoc:
  238. public var _rlmObjcValue: Any { persistableValue }
  239. }