RealmCollection.swift 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. ////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2014 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. /**
  21. An iterator for a `RealmCollection` instance.
  22. */
  23. public struct RLMIterator<Element: RealmCollectionValue>: IteratorProtocol {
  24. private var generatorBase: NSFastEnumerationIterator
  25. init(collection: RLMCollection) {
  26. generatorBase = NSFastEnumerationIterator(collection)
  27. }
  28. /// Advance to the next element and return it, or `nil` if no next element exists.
  29. public mutating func next() -> Element? {
  30. let next = generatorBase.next()
  31. if next is NSNull {
  32. return Element._nilValue()
  33. }
  34. if let next = next as? Object? {
  35. if next == nil {
  36. return nil as Element?
  37. }
  38. return unsafeBitCast(next, to: Optional<Element>.self)
  39. }
  40. return dynamicBridgeCast(fromObjectiveC: next as Any)
  41. }
  42. }
  43. /**
  44. A `RealmCollectionChange` value encapsulates information about changes to collections
  45. that are reported by Realm notifications.
  46. The change information is available in two formats: a simple array of row
  47. indices in the collection for each type of change, and an array of index paths
  48. in a requested section suitable for passing directly to `UITableView`'s batch
  49. update methods.
  50. The arrays of indices in the `.update` case follow `UITableView`'s batching
  51. conventions, and can be passed as-is to a table view's batch update functions after being converted to index paths.
  52. For example, for a simple one-section table view, you can do the following:
  53. ```swift
  54. self.notificationToken = results.observe { changes in
  55. switch changes {
  56. case .initial:
  57. // Results are now populated and can be accessed without blocking the UI
  58. self.tableView.reloadData()
  59. break
  60. case .update(_, let deletions, let insertions, let modifications):
  61. // Query results have changed, so apply them to the TableView
  62. self.tableView.beginUpdates()
  63. self.tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) },
  64. with: .automatic)
  65. self.tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) },
  66. with: .automatic)
  67. self.tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) },
  68. with: .automatic)
  69. self.tableView.endUpdates()
  70. break
  71. case .error(let err):
  72. // An error occurred while opening the Realm file on the background worker thread
  73. fatalError("\(err)")
  74. break
  75. }
  76. }
  77. ```
  78. */
  79. public enum RealmCollectionChange<CollectionType> {
  80. /**
  81. `.initial` indicates that the initial run of the query has completed (if
  82. applicable), and the collection can now be used without performing any
  83. blocking work.
  84. */
  85. case initial(CollectionType)
  86. /**
  87. `.update` indicates that a write transaction has been committed which
  88. either changed which objects are in the collection, and/or modified one
  89. or more of the objects in the collection.
  90. All three of the change arrays are always sorted in ascending order.
  91. - parameter deletions: The indices in the previous version of the collection which were removed from this one.
  92. - parameter insertions: The indices in the new collection which were added in this version.
  93. - parameter modifications: The indices of the objects in the new collection which were modified in this version.
  94. */
  95. case update(CollectionType, deletions: [Int], insertions: [Int], modifications: [Int])
  96. /**
  97. If an error occurs, notification blocks are called one time with a `.error`
  98. result and an `NSError` containing details about the error. This can only
  99. currently happen if opening the Realm on a background thread to calcuate
  100. the change set fails. The callback will never be called again after it is
  101. invoked with a .error value.
  102. */
  103. case error(Error)
  104. static func fromObjc(value: CollectionType, change: RLMCollectionChange?, error: Error?) -> RealmCollectionChange {
  105. if let error = error {
  106. return .error(error)
  107. }
  108. if let change = change {
  109. return .update(value,
  110. deletions: forceCast(change.deletions, to: [Int].self),
  111. insertions: forceCast(change.insertions, to: [Int].self),
  112. modifications: forceCast(change.modifications, to: [Int].self))
  113. }
  114. return .initial(value)
  115. }
  116. }
  117. private func forceCast<A, U>(_ from: A, to type: U.Type) -> U {
  118. return from as! U
  119. }
  120. /// A type which can be stored in a Realm List or Results.
  121. ///
  122. /// Declaring additional types as conforming to this protocol will not make them
  123. /// actually work. Most of the logic for how to store values in Realm is not
  124. /// implemented in Swift and there is currently no extension mechanism for
  125. /// supporting more types.
  126. public protocol RealmCollectionValue: Equatable {
  127. /// :nodoc:
  128. static func _rlmArray() -> RLMArray<AnyObject>
  129. /// :nodoc:
  130. static func _nilValue() -> Self
  131. }
  132. extension RealmCollectionValue {
  133. /// :nodoc:
  134. public static func _rlmArray() -> RLMArray<AnyObject> {
  135. return RLMArray(objectType: .int, optional: false)
  136. }
  137. /// :nodoc:
  138. public static func _nilValue() -> Self {
  139. fatalError("unexpected NSNull for non-Optional type")
  140. }
  141. }
  142. private func arrayType<T>(_ type: T.Type) -> RLMArray<AnyObject> {
  143. switch type {
  144. case is Int.Type, is Int8.Type, is Int16.Type, is Int32.Type, is Int64.Type:
  145. return RLMArray(objectType: .int, optional: true)
  146. case is Bool.Type: return RLMArray(objectType: .bool, optional: true)
  147. case is Float.Type: return RLMArray(objectType: .float, optional: true)
  148. case is Double.Type: return RLMArray(objectType: .double, optional: true)
  149. case is String.Type: return RLMArray(objectType: .string, optional: true)
  150. case is Data.Type: return RLMArray(objectType: .data, optional: true)
  151. case is Date.Type: return RLMArray(objectType: .date, optional: true)
  152. default: fatalError("Unsupported type for List: \(type)?")
  153. }
  154. }
  155. extension Optional: RealmCollectionValue where Wrapped: RealmCollectionValue {
  156. /// :nodoc:
  157. public static func _rlmArray() -> RLMArray<AnyObject> {
  158. return arrayType(Wrapped.self)
  159. }
  160. /// :nodoc:
  161. public static func _nilValue() -> Optional {
  162. return nil
  163. }
  164. }
  165. extension Int: RealmCollectionValue {}
  166. extension Int8: RealmCollectionValue {}
  167. extension Int16: RealmCollectionValue {}
  168. extension Int32: RealmCollectionValue {}
  169. extension Int64: RealmCollectionValue {}
  170. extension Float: RealmCollectionValue {
  171. /// :nodoc:
  172. public static func _rlmArray() -> RLMArray<AnyObject> {
  173. return RLMArray(objectType: .float, optional: false)
  174. }
  175. }
  176. extension Double: RealmCollectionValue {
  177. /// :nodoc:
  178. public static func _rlmArray() -> RLMArray<AnyObject> {
  179. return RLMArray(objectType: .double, optional: false)
  180. }
  181. }
  182. extension Bool: RealmCollectionValue {
  183. /// :nodoc:
  184. public static func _rlmArray() -> RLMArray<AnyObject> {
  185. return RLMArray(objectType: .bool, optional: false)
  186. }
  187. }
  188. extension String: RealmCollectionValue {
  189. /// :nodoc:
  190. public static func _rlmArray() -> RLMArray<AnyObject> {
  191. return RLMArray(objectType: .string, optional: false)
  192. }
  193. }
  194. extension Date: RealmCollectionValue {
  195. /// :nodoc:
  196. public static func _rlmArray() -> RLMArray<AnyObject> {
  197. return RLMArray(objectType: .date, optional: false)
  198. }
  199. }
  200. extension Data: RealmCollectionValue {
  201. /// :nodoc:
  202. public static func _rlmArray() -> RLMArray<AnyObject> {
  203. return RLMArray(objectType: .data, optional: false)
  204. }
  205. }
  206. /// :nodoc:
  207. public protocol _RealmCollectionEnumerator {
  208. // swiftlint:disable:next identifier_name
  209. func _asNSFastEnumerator() -> Any
  210. }
  211. /// :nodoc:
  212. public protocol RealmCollectionBase: RandomAccessCollection, LazyCollectionProtocol, CustomStringConvertible, ThreadConfined where Element: RealmCollectionValue {
  213. // This typealias was needed with Swift 3.1. It no longer is, but remains
  214. // just in case someone was depending on it
  215. typealias ElementType = Element
  216. }
  217. /**
  218. A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon.
  219. */
  220. public protocol RealmCollection: RealmCollectionBase, _RealmCollectionEnumerator {
  221. // Must also conform to `AssistedObjectiveCBridgeable`
  222. // MARK: Properties
  223. /// The Realm which manages the collection, or `nil` for unmanaged collections.
  224. var realm: Realm? { get }
  225. /**
  226. Indicates if the collection can no longer be accessed.
  227. The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection.
  228. */
  229. var isInvalidated: Bool { get }
  230. /// The number of objects in the collection.
  231. var count: Int { get }
  232. /// A human-readable description of the objects contained in the collection.
  233. var description: String { get }
  234. // MARK: Index Retrieval
  235. /**
  236. Returns the index of an object in the collection, or `nil` if the object is not present.
  237. - parameter object: An object.
  238. */
  239. func index(of object: Element) -> Int?
  240. /**
  241. Returns the index of the first object matching the predicate, or `nil` if no objects match.
  242. - parameter predicate: The predicate to use to filter the objects.
  243. */
  244. func index(matching predicate: NSPredicate) -> Int?
  245. /**
  246. Returns the index of the first object matching the predicate, or `nil` if no objects match.
  247. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  248. */
  249. func index(matching predicateFormat: String, _ args: Any...) -> Int?
  250. // MARK: Filtering
  251. /**
  252. Returns a `Results` containing all objects matching the given predicate in the collection.
  253. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  254. */
  255. func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element>
  256. /**
  257. Returns a `Results` containing all objects matching the given predicate in the collection.
  258. - parameter predicate: The predicate to use to filter the objects.
  259. */
  260. func filter(_ predicate: NSPredicate) -> Results<Element>
  261. // MARK: Sorting
  262. /**
  263. Returns a `Results` containing the objects in the collection, but sorted.
  264. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
  265. youngest to oldest based on their `age` property, you might call
  266. `students.sorted(byKeyPath: "age", ascending: true)`.
  267. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  268. floating point, integer, and string types.
  269. - parameter keyPath: The key path to sort by.
  270. - parameter ascending: The direction to sort in.
  271. */
  272. func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element>
  273. /**
  274. Returns a `Results` containing the objects in the collection, but sorted.
  275. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  276. floating point, integer, and string types.
  277. - see: `sorted(byKeyPath:ascending:)`
  278. - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
  279. */
  280. func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor
  281. // MARK: Aggregate Operations
  282. /**
  283. Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
  284. collection is empty.
  285. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  286. - parameter property: The name of a property whose minimum value is desired.
  287. */
  288. func min<T: MinMaxType>(ofProperty property: String) -> T?
  289. /**
  290. Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
  291. collection is empty.
  292. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  293. - parameter property: The name of a property whose minimum value is desired.
  294. */
  295. func max<T: MinMaxType>(ofProperty property: String) -> T?
  296. /**
  297. Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty.
  298. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
  299. - parameter property: The name of a property conforming to `AddableType` to calculate sum on.
  300. */
  301. func sum<T: AddableType>(ofProperty property: String) -> T
  302. /**
  303. Returns the average value of a given property over all the objects in the collection, or `nil` if
  304. the collection is empty.
  305. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  306. - parameter property: The name of a property whose values should be summed.
  307. */
  308. func average(ofProperty property: String) -> Double?
  309. // MARK: Key-Value Coding
  310. /**
  311. Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
  312. objects.
  313. - parameter key: The name of the property whose values are desired.
  314. */
  315. func value(forKey key: String) -> Any?
  316. /**
  317. Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
  318. collection's objects.
  319. - parameter keyPath: The key path to the property whose values are desired.
  320. */
  321. func value(forKeyPath keyPath: String) -> Any?
  322. /**
  323. Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
  324. - warning: This method may only be called during a write transaction.
  325. - parameter value: The object value.
  326. - parameter key: The name of the property whose value should be set on each object.
  327. */
  328. func setValue(_ value: Any?, forKey key: String)
  329. // MARK: Notifications
  330. /**
  331. Registers a block to be called each time the collection changes.
  332. The block will be asynchronously called with the initial results, and then called again after each write
  333. transaction which changes either any of the objects in the collection, or which objects are in the collection.
  334. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
  335. the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
  336. documentation for more information on the change information supplied and an example of how to use it to update a
  337. `UITableView`.
  338. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
  339. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  340. perform blocking work.
  341. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
  342. other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
  343. single notification. This can include the notification with the initial collection.
  344. For example, the following code performs a write transaction immediately after adding the notification block, so
  345. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  346. will reflect the state of the Realm after the write transaction.
  347. ```swift
  348. let results = realm.objects(Dog.self)
  349. print("dogs.count: \(dogs?.count)") // => 0
  350. let token = dogs.observe { changes in
  351. switch changes {
  352. case .initial(let dogs):
  353. // Will print "dogs.count: 1"
  354. print("dogs.count: \(dogs.count)")
  355. break
  356. case .update:
  357. // Will not be hit in this example
  358. break
  359. case .error:
  360. break
  361. }
  362. }
  363. try! realm.write {
  364. let dog = Dog()
  365. dog.name = "Rex"
  366. person.dogs.append(dog)
  367. }
  368. // end of run loop execution context
  369. ```
  370. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  371. updates, call `invalidate()` on the token.
  372. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  373. - parameter block: The block to be called whenever a change occurs.
  374. - returns: A token which must be held for as long as you want updates to be delivered.
  375. */
  376. func observe(_ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken
  377. /// :nodoc:
  378. func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken
  379. }
  380. /// :nodoc:
  381. public protocol OptionalProtocol {
  382. associatedtype Wrapped
  383. /// :nodoc:
  384. // swiftlint:disable:next identifier_name
  385. func _rlmInferWrappedType() -> Wrapped
  386. }
  387. extension Optional: OptionalProtocol {
  388. /// :nodoc:
  389. // swiftlint:disable:next identifier_name
  390. public func _rlmInferWrappedType() -> Wrapped { return self! }
  391. }
  392. public extension RealmCollection where Element: MinMaxType {
  393. /**
  394. Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
  395. */
  396. func min() -> Element? {
  397. return min(ofProperty: "self")
  398. }
  399. /**
  400. Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
  401. */
  402. func max() -> Element? {
  403. return max(ofProperty: "self")
  404. }
  405. }
  406. public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: MinMaxType {
  407. /**
  408. Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
  409. */
  410. func min() -> Element.Wrapped? {
  411. return min(ofProperty: "self")
  412. }
  413. /**
  414. Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
  415. */
  416. func max() -> Element.Wrapped? {
  417. return max(ofProperty: "self")
  418. }
  419. }
  420. public extension RealmCollection where Element: AddableType {
  421. /**
  422. Returns the sum of the values in the collection, or `nil` if the collection is empty.
  423. */
  424. func sum() -> Element {
  425. return sum(ofProperty: "self")
  426. }
  427. /**
  428. Returns the average of all of the values in the collection.
  429. */
  430. func average() -> Double? {
  431. return average(ofProperty: "self")
  432. }
  433. }
  434. public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: AddableType {
  435. /**
  436. Returns the sum of the values in the collection, or `nil` if the collection is empty.
  437. */
  438. func sum() -> Element.Wrapped {
  439. return sum(ofProperty: "self")
  440. }
  441. /**
  442. Returns the average of all of the values in the collection.
  443. */
  444. func average() -> Double? {
  445. return average(ofProperty: "self")
  446. }
  447. }
  448. public extension RealmCollection where Element: Comparable {
  449. /**
  450. Returns a `Results` containing the objects in the collection, but sorted.
  451. Objects are sorted based on their values. For example, to sort a collection of `Date`s from
  452. neweset to oldest based, you might call `dates.sorted(ascending: true)`.
  453. - parameter ascending: The direction to sort in.
  454. */
  455. func sorted(ascending: Bool = true) -> Results<Element> {
  456. return sorted(byKeyPath: "self", ascending: ascending)
  457. }
  458. }
  459. public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: Comparable {
  460. /**
  461. Returns a `Results` containing the objects in the collection, but sorted.
  462. Objects are sorted based on their values. For example, to sort a collection of `Date`s from
  463. neweset to oldest based, you might call `dates.sorted(ascending: true)`.
  464. - parameter ascending: The direction to sort in.
  465. */
  466. func sorted(ascending: Bool = true) -> Results<Element> {
  467. return sorted(byKeyPath: "self", ascending: ascending)
  468. }
  469. }
  470. private class _AnyRealmCollectionBase<T: RealmCollectionValue>: AssistedObjectiveCBridgeable {
  471. typealias Wrapper = AnyRealmCollection<Element>
  472. typealias Element = T
  473. var realm: Realm? { fatalError() }
  474. var isInvalidated: Bool { fatalError() }
  475. var count: Int { fatalError() }
  476. var description: String { fatalError() }
  477. func index(of object: Element) -> Int? { fatalError() }
  478. func index(matching predicate: NSPredicate) -> Int? { fatalError() }
  479. func index(matching predicateFormat: String, _ args: Any...) -> Int? { fatalError() }
  480. func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { fatalError() }
  481. func filter(_ predicate: NSPredicate) -> Results<Element> { fatalError() }
  482. func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> { fatalError() }
  483. func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor {
  484. fatalError()
  485. }
  486. func min<T: MinMaxType>(ofProperty property: String) -> T? { fatalError() }
  487. func max<T: MinMaxType>(ofProperty property: String) -> T? { fatalError() }
  488. func sum<T: AddableType>(ofProperty property: String) -> T { fatalError() }
  489. func average(ofProperty property: String) -> Double? { fatalError() }
  490. subscript(position: Int) -> Element { fatalError() }
  491. func makeIterator() -> RLMIterator<T> { fatalError() }
  492. var startIndex: Int { fatalError() }
  493. var endIndex: Int { fatalError() }
  494. func value(forKey key: String) -> Any? { fatalError() }
  495. func value(forKeyPath keyPath: String) -> Any? { fatalError() }
  496. func setValue(_ value: Any?, forKey key: String) { fatalError() }
  497. func _observe(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
  498. -> NotificationToken { fatalError() }
  499. class func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self { fatalError() }
  500. var bridged: (objectiveCValue: Any, metadata: Any?) { fatalError() }
  501. // swiftlint:disable:next identifier_name
  502. func _asNSFastEnumerator() -> Any { fatalError() }
  503. }
  504. private final class _AnyRealmCollection<C: RealmCollection>: _AnyRealmCollectionBase<C.Element> {
  505. let base: C
  506. init(base: C) {
  507. self.base = base
  508. }
  509. // MARK: Properties
  510. override var realm: Realm? { return base.realm }
  511. override var isInvalidated: Bool { return base.isInvalidated }
  512. override var count: Int { return base.count }
  513. override var description: String { return base.description }
  514. // MARK: Index Retrieval
  515. override func index(of object: C.Element) -> Int? { return base.index(of: object) }
  516. override func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
  517. override func index(matching predicateFormat: String, _ args: Any...) -> Int? {
  518. return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  519. }
  520. // MARK: Filtering
  521. override func filter(_ predicateFormat: String, _ args: Any...) -> Results<C.Element> {
  522. return base.filter(NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  523. }
  524. override func filter(_ predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) }
  525. // MARK: Sorting
  526. override func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<C.Element> {
  527. return base.sorted(byKeyPath: keyPath, ascending: ascending)
  528. }
  529. override func sorted<S: Sequence>
  530. (by sortDescriptors: S) -> Results<C.Element> where S.Iterator.Element == SortDescriptor {
  531. return base.sorted(by: sortDescriptors)
  532. }
  533. // MARK: Aggregate Operations
  534. override func min<T: MinMaxType>(ofProperty property: String) -> T? {
  535. return base.min(ofProperty: property)
  536. }
  537. override func max<T: MinMaxType>(ofProperty property: String) -> T? {
  538. return base.max(ofProperty: property)
  539. }
  540. override func sum<T: AddableType>(ofProperty property: String) -> T {
  541. return base.sum(ofProperty: property)
  542. }
  543. override func average(ofProperty property: String) -> Double? {
  544. return base.average(ofProperty: property)
  545. }
  546. // MARK: Sequence Support
  547. override subscript(position: Int) -> C.Element {
  548. return base[position as! C.Index]
  549. }
  550. override func makeIterator() -> RLMIterator<Element> {
  551. // FIXME: it should be possible to avoid this force-casting
  552. return base.makeIterator() as! RLMIterator<Element>
  553. }
  554. /// :nodoc:
  555. override func _asNSFastEnumerator() -> Any {
  556. return base._asNSFastEnumerator()
  557. }
  558. // MARK: Collection Support
  559. override var startIndex: Int {
  560. // FIXME: it should be possible to avoid this force-casting
  561. return base.startIndex as! Int
  562. }
  563. override var endIndex: Int {
  564. // FIXME: it should be possible to avoid this force-casting
  565. return base.endIndex as! Int
  566. }
  567. // MARK: Key-Value Coding
  568. override func value(forKey key: String) -> Any? { return base.value(forKey: key) }
  569. override func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
  570. override func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
  571. // MARK: Notifications
  572. /// :nodoc:
  573. override func _observe(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
  574. -> NotificationToken { return base._observe(block) }
  575. // MARK: AssistedObjectiveCBridgeable
  576. override class func bridging(from objectiveCValue: Any, with metadata: Any?) -> _AnyRealmCollection {
  577. return _AnyRealmCollection(
  578. base: (C.self as! AssistedObjectiveCBridgeable.Type).bridging(from: objectiveCValue, with: metadata) as! C)
  579. }
  580. override var bridged: (objectiveCValue: Any, metadata: Any?) {
  581. return (base as! AssistedObjectiveCBridgeable).bridged
  582. }
  583. }
  584. /**
  585. A type-erased `RealmCollection`.
  586. Instances of `RealmCollection` forward operations to an opaque underlying collection having the same `Element` type.
  587. */
  588. public struct AnyRealmCollection<Element: RealmCollectionValue>: RealmCollection {
  589. /// The type of the objects contained within the collection.
  590. public typealias ElementType = Element
  591. public func index(after i: Int) -> Int { return i + 1 }
  592. public func index(before i: Int) -> Int { return i - 1 }
  593. /// The type of the objects contained in the collection.
  594. fileprivate let base: _AnyRealmCollectionBase<Element>
  595. fileprivate init(base: _AnyRealmCollectionBase<Element>) {
  596. self.base = base
  597. }
  598. /// Creates an `AnyRealmCollection` wrapping `base`.
  599. public init<C: RealmCollection>(_ base: C) where C.Element == Element {
  600. self.base = _AnyRealmCollection(base: base)
  601. }
  602. // MARK: Properties
  603. /// The Realm which manages the collection, or `nil` if the collection is unmanaged.
  604. public var realm: Realm? { return base.realm }
  605. /**
  606. Indicates if the collection can no longer be accessed.
  607. The collection can no longer be accessed if `invalidate()` is called on the containing `realm`.
  608. */
  609. public var isInvalidated: Bool { return base.isInvalidated }
  610. /// The number of objects in the collection.
  611. public var count: Int { return base.count }
  612. /// A human-readable description of the objects contained in the collection.
  613. public var description: String { return base.description }
  614. // MARK: Index Retrieval
  615. /**
  616. Returns the index of the given object, or `nil` if the object is not in the collection.
  617. - parameter object: An object.
  618. */
  619. public func index(of object: Element) -> Int? { return base.index(of: object) }
  620. /**
  621. Returns the index of the first object matching the given predicate, or `nil` if no objects match.
  622. - parameter predicate: The predicate with which to filter the objects.
  623. */
  624. public func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
  625. /**
  626. Returns the index of the first object matching the given predicate, or `nil` if no objects match.
  627. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  628. */
  629. public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
  630. return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  631. }
  632. // MARK: Filtering
  633. /**
  634. Returns a `Results` containing all objects matching the given predicate in the collection.
  635. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  636. */
  637. public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
  638. return base.filter(NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  639. }
  640. /**
  641. Returns a `Results` containing all objects matching the given predicate in the collection.
  642. - parameter predicate: The predicate with which to filter the objects.
  643. - returns: A `Results` containing objects that match the given predicate.
  644. */
  645. public func filter(_ predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) }
  646. // MARK: Sorting
  647. /**
  648. Returns a `Results` containing the objects in the collection, but sorted.
  649. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
  650. youngest to oldest based on their `age` property, you might call
  651. `students.sorted(byKeyPath: "age", ascending: true)`.
  652. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  653. floating point, integer, and string types.
  654. - parameter keyPath: The key path to sort by.
  655. - parameter ascending: The direction to sort in.
  656. */
  657. public func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> {
  658. return base.sorted(byKeyPath: keyPath, ascending: ascending)
  659. }
  660. /**
  661. Returns a `Results` containing the objects in the collection, but sorted.
  662. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  663. floating point, integer, and string types.
  664. - see: `sorted(byKeyPath:ascending:)`
  665. - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
  666. */
  667. public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
  668. where S.Iterator.Element == SortDescriptor {
  669. return base.sorted(by: sortDescriptors)
  670. }
  671. // MARK: Aggregate Operations
  672. /**
  673. Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
  674. collection is empty.
  675. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  676. - parameter property: The name of a property whose minimum value is desired.
  677. */
  678. public func min<T: MinMaxType>(ofProperty property: String) -> T? {
  679. return base.min(ofProperty: property)
  680. }
  681. /**
  682. Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
  683. collection is empty.
  684. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  685. - parameter property: The name of a property whose minimum value is desired.
  686. */
  687. public func max<T: MinMaxType>(ofProperty property: String) -> T? {
  688. return base.max(ofProperty: property)
  689. }
  690. /**
  691. Returns the sum of the values of a given property over all the objects in the collection.
  692. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  693. - parameter property: The name of a property whose values should be summed.
  694. */
  695. public func sum<T: AddableType>(ofProperty property: String) -> T { return base.sum(ofProperty: property) }
  696. /**
  697. Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is
  698. empty.
  699. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
  700. - parameter property: The name of a property whose average value should be calculated.
  701. */
  702. public func average(ofProperty property: String) -> Double? { return base.average(ofProperty: property) }
  703. // MARK: Sequence Support
  704. /**
  705. Returns the object at the given `index`.
  706. - parameter index: The index.
  707. */
  708. public subscript(position: Int) -> Element { return base[position] }
  709. /// Returns a `RLMIterator` that yields successive elements in the collection.
  710. public func makeIterator() -> RLMIterator<Element> { return base.makeIterator() }
  711. /// :nodoc:
  712. // swiftlint:disable:next identifier_name
  713. public func _asNSFastEnumerator() -> Any { return base._asNSFastEnumerator() }
  714. // MARK: Collection Support
  715. /// The position of the first element in a non-empty collection.
  716. /// Identical to endIndex in an empty collection.
  717. public var startIndex: Int { return base.startIndex }
  718. /// The collection's "past the end" position.
  719. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
  720. /// zero or more applications of successor().
  721. public var endIndex: Int { return base.endIndex }
  722. // MARK: Key-Value Coding
  723. /**
  724. Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
  725. objects.
  726. - parameter key: The name of the property whose values are desired.
  727. */
  728. public func value(forKey key: String) -> Any? { return base.value(forKey: key) }
  729. /**
  730. Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
  731. collection's objects.
  732. - parameter keyPath: The key path to the property whose values are desired.
  733. */
  734. public func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
  735. /**
  736. Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
  737. - warning: This method may only be called during a write transaction.
  738. - parameter value: The value to set the property to.
  739. - parameter key: The name of the property whose value should be set on each object.
  740. */
  741. public func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
  742. // MARK: Notifications
  743. /**
  744. Registers a block to be called each time the collection changes.
  745. The block will be asynchronously called with the initial results, and then called again after each write
  746. transaction which changes either any of the objects in the collection, or which objects are in the collection.
  747. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
  748. the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
  749. documentation for more information on the change information supplied and an example of how to use it to update a
  750. `UITableView`.
  751. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
  752. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  753. perform blocking work.
  754. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
  755. other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
  756. single notification. This can include the notification with the initial collection.
  757. For example, the following code performs a write transaction immediately after adding the notification block, so
  758. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  759. will reflect the state of the Realm after the write transaction.
  760. ```swift
  761. let results = realm.objects(Dog.self)
  762. print("dogs.count: \(dogs?.count)") // => 0
  763. let token = dogs.observe { changes in
  764. switch changes {
  765. case .initial(let dogs):
  766. // Will print "dogs.count: 1"
  767. print("dogs.count: \(dogs.count)")
  768. break
  769. case .update:
  770. // Will not be hit in this example
  771. break
  772. case .error:
  773. break
  774. }
  775. }
  776. try! realm.write {
  777. let dog = Dog()
  778. dog.name = "Rex"
  779. person.dogs.append(dog)
  780. }
  781. // end of run loop execution context
  782. ```
  783. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  784. updates, call `invalidate()` on the token.
  785. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  786. - parameter block: The block to be called whenever a change occurs.
  787. - returns: A token which must be held for as long as you want updates to be delivered.
  788. */
  789. public func observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
  790. -> NotificationToken { return base._observe(block) }
  791. /// :nodoc:
  792. public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
  793. -> NotificationToken { return base._observe(block) }
  794. }
  795. // MARK: AssistedObjectiveCBridgeable
  796. private struct AnyRealmCollectionBridgingMetadata<T: RealmCollectionValue> {
  797. var baseMetadata: Any?
  798. var baseType: _AnyRealmCollectionBase<T>.Type
  799. }
  800. extension AnyRealmCollection: AssistedObjectiveCBridgeable {
  801. internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> AnyRealmCollection {
  802. guard let metadata = metadata as? AnyRealmCollectionBridgingMetadata<Element> else { preconditionFailure() }
  803. return AnyRealmCollection(base: metadata.baseType.bridging(from: objectiveCValue, with: metadata.baseMetadata))
  804. }
  805. internal var bridged: (objectiveCValue: Any, metadata: Any?) {
  806. return (
  807. objectiveCValue: base.bridged.objectiveCValue,
  808. metadata: AnyRealmCollectionBridgingMetadata(baseMetadata: base.bridged.metadata, baseType: type(of: base))
  809. )
  810. }
  811. }