RealmCollection.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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 RealmCollectionBase: RandomAccessCollection, LazyCollectionProtocol, CustomStringConvertible, ThreadConfined where Element: RealmCollectionValue {
  208. // This typealias was needed with Swift 3.1. It no longer is, but remains
  209. // just in case someone was depending on it
  210. typealias ElementType = Element
  211. }
  212. /**
  213. A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon.
  214. */
  215. public protocol RealmCollection: RealmCollectionBase {
  216. // Must also conform to `AssistedObjectiveCBridgeable`
  217. // MARK: Properties
  218. /// The Realm which manages the collection, or `nil` for unmanaged collections.
  219. var realm: Realm? { get }
  220. /**
  221. Indicates if the collection can no longer be accessed.
  222. The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection.
  223. */
  224. var isInvalidated: Bool { get }
  225. /// The number of objects in the collection.
  226. var count: Int { get }
  227. /// A human-readable description of the objects contained in the collection.
  228. var description: String { get }
  229. // MARK: Index Retrieval
  230. /**
  231. Returns the index of an object in the collection, or `nil` if the object is not present.
  232. - parameter object: An object.
  233. */
  234. func index(of object: Element) -> Int?
  235. /**
  236. Returns the index of the first object matching the predicate, or `nil` if no objects match.
  237. - parameter predicate: The predicate to use to filter the objects.
  238. */
  239. func index(matching predicate: NSPredicate) -> Int?
  240. /**
  241. Returns the index of the first object matching the predicate, or `nil` if no objects match.
  242. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  243. */
  244. func index(matching predicateFormat: String, _ args: Any...) -> Int?
  245. // MARK: Filtering
  246. /**
  247. Returns a `Results` containing all objects matching the given predicate in the collection.
  248. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  249. */
  250. func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element>
  251. /**
  252. Returns a `Results` containing all objects matching the given predicate in the collection.
  253. - parameter predicate: The predicate to use to filter the objects.
  254. */
  255. func filter(_ predicate: NSPredicate) -> Results<Element>
  256. // MARK: Sorting
  257. /**
  258. Returns a `Results` containing the objects in the collection, but sorted.
  259. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
  260. youngest to oldest based on their `age` property, you might call
  261. `students.sorted(byKeyPath: "age", ascending: true)`.
  262. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  263. floating point, integer, and string types.
  264. - parameter keyPath: The key path to sort by.
  265. - parameter ascending: The direction to sort in.
  266. */
  267. func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element>
  268. /**
  269. Returns a `Results` containing the objects in the collection, but sorted.
  270. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  271. floating point, integer, and string types.
  272. - see: `sorted(byKeyPath:ascending:)`
  273. - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
  274. */
  275. func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor
  276. // MARK: Aggregate Operations
  277. /**
  278. Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
  279. collection is empty.
  280. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  281. - parameter property: The name of a property whose minimum value is desired.
  282. */
  283. func min<T: MinMaxType>(ofProperty property: String) -> T?
  284. /**
  285. Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
  286. collection is empty.
  287. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  288. - parameter property: The name of a property whose minimum value is desired.
  289. */
  290. func max<T: MinMaxType>(ofProperty property: String) -> T?
  291. /**
  292. Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty.
  293. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
  294. - parameter property: The name of a property conforming to `AddableType` to calculate sum on.
  295. */
  296. func sum<T: AddableType>(ofProperty property: String) -> T
  297. /**
  298. Returns the average value of a given property over all the objects in the collection, or `nil` if
  299. the collection is empty.
  300. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  301. - parameter property: The name of a property whose values should be summed.
  302. */
  303. func average(ofProperty property: String) -> Double?
  304. // MARK: Key-Value Coding
  305. /**
  306. Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
  307. objects.
  308. - parameter key: The name of the property whose values are desired.
  309. */
  310. func value(forKey key: String) -> Any?
  311. /**
  312. Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
  313. collection's objects.
  314. - parameter keyPath: The key path to the property whose values are desired.
  315. */
  316. func value(forKeyPath keyPath: String) -> Any?
  317. /**
  318. Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
  319. - warning: This method may only be called during a write transaction.
  320. - parameter value: The object value.
  321. - parameter key: The name of the property whose value should be set on each object.
  322. */
  323. func setValue(_ value: Any?, forKey key: String)
  324. // MARK: Notifications
  325. /**
  326. Registers a block to be called each time the collection changes.
  327. The block will be asynchronously called with the initial results, and then called again after each write
  328. transaction which changes either any of the objects in the collection, or which objects are in the collection.
  329. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
  330. the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
  331. documentation for more information on the change information supplied and an example of how to use it to update a
  332. `UITableView`.
  333. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
  334. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  335. perform blocking work.
  336. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
  337. other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
  338. single notification. This can include the notification with the initial collection.
  339. For example, the following code performs a write transaction immediately after adding the notification block, so
  340. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  341. will reflect the state of the Realm after the write transaction.
  342. ```swift
  343. let results = realm.objects(Dog.self)
  344. print("dogs.count: \(dogs?.count)") // => 0
  345. let token = dogs.observe { changes in
  346. switch changes {
  347. case .initial(let dogs):
  348. // Will print "dogs.count: 1"
  349. print("dogs.count: \(dogs.count)")
  350. break
  351. case .update:
  352. // Will not be hit in this example
  353. break
  354. case .error:
  355. break
  356. }
  357. }
  358. try! realm.write {
  359. let dog = Dog()
  360. dog.name = "Rex"
  361. person.dogs.append(dog)
  362. }
  363. // end of run loop execution context
  364. ```
  365. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  366. updates, call `invalidate()` on the token.
  367. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  368. - parameter block: The block to be called whenever a change occurs.
  369. - returns: A token which must be held for as long as you want updates to be delivered.
  370. */
  371. func observe(_ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken
  372. /// :nodoc:
  373. func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken
  374. }
  375. /// :nodoc:
  376. public protocol OptionalProtocol {
  377. associatedtype Wrapped
  378. /// :nodoc:
  379. // swiftlint:disable:next identifier_name
  380. func _rlmInferWrappedType() -> Wrapped
  381. }
  382. extension Optional: OptionalProtocol {
  383. /// :nodoc:
  384. // swiftlint:disable:next identifier_name
  385. public func _rlmInferWrappedType() -> Wrapped { return self! }
  386. }
  387. public extension RealmCollection where Element: MinMaxType {
  388. /**
  389. Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
  390. */
  391. func min() -> Element? {
  392. return min(ofProperty: "self")
  393. }
  394. /**
  395. Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
  396. */
  397. func max() -> Element? {
  398. return max(ofProperty: "self")
  399. }
  400. }
  401. public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: MinMaxType {
  402. /**
  403. Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
  404. */
  405. func min() -> Element.Wrapped? {
  406. return min(ofProperty: "self")
  407. }
  408. /**
  409. Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
  410. */
  411. func max() -> Element.Wrapped? {
  412. return max(ofProperty: "self")
  413. }
  414. }
  415. public extension RealmCollection where Element: AddableType {
  416. /**
  417. Returns the sum of the values in the collection, or `nil` if the collection is empty.
  418. */
  419. func sum() -> Element {
  420. return sum(ofProperty: "self")
  421. }
  422. /**
  423. Returns the average of all of the values in the collection.
  424. */
  425. func average() -> Double? {
  426. return average(ofProperty: "self")
  427. }
  428. }
  429. public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: AddableType {
  430. /**
  431. Returns the sum of the values in the collection, or `nil` if the collection is empty.
  432. */
  433. func sum() -> Element.Wrapped {
  434. return sum(ofProperty: "self")
  435. }
  436. /**
  437. Returns the average of all of the values in the collection.
  438. */
  439. func average() -> Double? {
  440. return average(ofProperty: "self")
  441. }
  442. }
  443. public extension RealmCollection where Element: Comparable {
  444. /**
  445. Returns a `Results` containing the objects in the collection, but sorted.
  446. Objects are sorted based on their values. For example, to sort a collection of `Date`s from
  447. neweset to oldest based, you might call `dates.sorted(ascending: true)`.
  448. - parameter ascending: The direction to sort in.
  449. */
  450. func sorted(ascending: Bool = true) -> Results<Element> {
  451. return sorted(byKeyPath: "self", ascending: ascending)
  452. }
  453. }
  454. public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: Comparable {
  455. /**
  456. Returns a `Results` containing the objects in the collection, but sorted.
  457. Objects are sorted based on their values. For example, to sort a collection of `Date`s from
  458. neweset to oldest based, you might call `dates.sorted(ascending: true)`.
  459. - parameter ascending: The direction to sort in.
  460. */
  461. func sorted(ascending: Bool = true) -> Results<Element> {
  462. return sorted(byKeyPath: "self", ascending: ascending)
  463. }
  464. }
  465. private class _AnyRealmCollectionBase<T: RealmCollectionValue>: AssistedObjectiveCBridgeable {
  466. typealias Wrapper = AnyRealmCollection<Element>
  467. typealias Element = T
  468. var realm: Realm? { fatalError() }
  469. var isInvalidated: Bool { fatalError() }
  470. var count: Int { fatalError() }
  471. var description: String { fatalError() }
  472. func index(of object: Element) -> Int? { fatalError() }
  473. func index(matching predicate: NSPredicate) -> Int? { fatalError() }
  474. func index(matching predicateFormat: String, _ args: Any...) -> Int? { fatalError() }
  475. func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { fatalError() }
  476. func filter(_ predicate: NSPredicate) -> Results<Element> { fatalError() }
  477. func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> { fatalError() }
  478. func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor {
  479. fatalError()
  480. }
  481. func min<T: MinMaxType>(ofProperty property: String) -> T? { fatalError() }
  482. func max<T: MinMaxType>(ofProperty property: String) -> T? { fatalError() }
  483. func sum<T: AddableType>(ofProperty property: String) -> T { fatalError() }
  484. func average(ofProperty property: String) -> Double? { fatalError() }
  485. subscript(position: Int) -> Element { fatalError() }
  486. func makeIterator() -> RLMIterator<T> { fatalError() }
  487. var startIndex: Int { fatalError() }
  488. var endIndex: Int { fatalError() }
  489. func value(forKey key: String) -> Any? { fatalError() }
  490. func value(forKeyPath keyPath: String) -> Any? { fatalError() }
  491. func setValue(_ value: Any?, forKey key: String) { fatalError() }
  492. func _observe(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
  493. -> NotificationToken { fatalError() }
  494. class func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self { fatalError() }
  495. var bridged: (objectiveCValue: Any, metadata: Any?) { fatalError() }
  496. }
  497. private final class _AnyRealmCollection<C: RealmCollection>: _AnyRealmCollectionBase<C.Element> {
  498. let base: C
  499. init(base: C) {
  500. self.base = base
  501. }
  502. // MARK: Properties
  503. override var realm: Realm? { return base.realm }
  504. override var isInvalidated: Bool { return base.isInvalidated }
  505. override var count: Int { return base.count }
  506. override var description: String { return base.description }
  507. // MARK: Index Retrieval
  508. override func index(of object: C.Element) -> Int? { return base.index(of: object) }
  509. override func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
  510. override func index(matching predicateFormat: String, _ args: Any...) -> Int? {
  511. return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  512. }
  513. // MARK: Filtering
  514. override func filter(_ predicateFormat: String, _ args: Any...) -> Results<C.Element> {
  515. return base.filter(NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  516. }
  517. override func filter(_ predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) }
  518. // MARK: Sorting
  519. override func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<C.Element> {
  520. return base.sorted(byKeyPath: keyPath, ascending: ascending)
  521. }
  522. override func sorted<S: Sequence>
  523. (by sortDescriptors: S) -> Results<C.Element> where S.Iterator.Element == SortDescriptor {
  524. return base.sorted(by: sortDescriptors)
  525. }
  526. // MARK: Aggregate Operations
  527. override func min<T: MinMaxType>(ofProperty property: String) -> T? {
  528. return base.min(ofProperty: property)
  529. }
  530. override func max<T: MinMaxType>(ofProperty property: String) -> T? {
  531. return base.max(ofProperty: property)
  532. }
  533. override func sum<T: AddableType>(ofProperty property: String) -> T {
  534. return base.sum(ofProperty: property)
  535. }
  536. override func average(ofProperty property: String) -> Double? {
  537. return base.average(ofProperty: property)
  538. }
  539. // MARK: Sequence Support
  540. override subscript(position: Int) -> C.Element {
  541. return base[position as! C.Index]
  542. }
  543. override func makeIterator() -> RLMIterator<Element> {
  544. // FIXME: it should be possible to avoid this force-casting
  545. return base.makeIterator() as! RLMIterator<Element>
  546. }
  547. // MARK: Collection Support
  548. override var startIndex: Int {
  549. // FIXME: it should be possible to avoid this force-casting
  550. return base.startIndex as! Int
  551. }
  552. override var endIndex: Int {
  553. // FIXME: it should be possible to avoid this force-casting
  554. return base.endIndex as! Int
  555. }
  556. // MARK: Key-Value Coding
  557. override func value(forKey key: String) -> Any? { return base.value(forKey: key) }
  558. override func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
  559. override func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
  560. // MARK: Notifications
  561. /// :nodoc:
  562. override func _observe(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
  563. -> NotificationToken { return base._observe(block) }
  564. // MARK: AssistedObjectiveCBridgeable
  565. override class func bridging(from objectiveCValue: Any, with metadata: Any?) -> _AnyRealmCollection {
  566. return _AnyRealmCollection(
  567. base: (C.self as! AssistedObjectiveCBridgeable.Type).bridging(from: objectiveCValue, with: metadata) as! C)
  568. }
  569. override var bridged: (objectiveCValue: Any, metadata: Any?) {
  570. return (base as! AssistedObjectiveCBridgeable).bridged
  571. }
  572. }
  573. /**
  574. A type-erased `RealmCollection`.
  575. Instances of `RealmCollection` forward operations to an opaque underlying collection having the same `Element` type.
  576. */
  577. public final class AnyRealmCollection<Element: RealmCollectionValue>: RealmCollection {
  578. /// The type of the objects contained within the collection.
  579. public typealias ElementType = Element
  580. public func index(after i: Int) -> Int { return i + 1 }
  581. public func index(before i: Int) -> Int { return i - 1 }
  582. /// The type of the objects contained in the collection.
  583. fileprivate let base: _AnyRealmCollectionBase<Element>
  584. fileprivate init(base: _AnyRealmCollectionBase<Element>) {
  585. self.base = base
  586. }
  587. /// Creates an `AnyRealmCollection` wrapping `base`.
  588. public init<C: RealmCollection>(_ base: C) where C.Element == Element {
  589. self.base = _AnyRealmCollection(base: base)
  590. }
  591. // MARK: Properties
  592. /// The Realm which manages the collection, or `nil` if the collection is unmanaged.
  593. public var realm: Realm? { return base.realm }
  594. /**
  595. Indicates if the collection can no longer be accessed.
  596. The collection can no longer be accessed if `invalidate()` is called on the containing `realm`.
  597. */
  598. public var isInvalidated: Bool { return base.isInvalidated }
  599. /// The number of objects in the collection.
  600. public var count: Int { return base.count }
  601. /// A human-readable description of the objects contained in the collection.
  602. public var description: String { return base.description }
  603. // MARK: Index Retrieval
  604. /**
  605. Returns the index of the given object, or `nil` if the object is not in the collection.
  606. - parameter object: An object.
  607. */
  608. public func index(of object: Element) -> Int? { return base.index(of: object) }
  609. /**
  610. Returns the index of the first object matching the given predicate, or `nil` if no objects match.
  611. - parameter predicate: The predicate with which to filter the objects.
  612. */
  613. public func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
  614. /**
  615. Returns the index of the first object matching the given predicate, or `nil` if no objects match.
  616. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  617. */
  618. public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
  619. return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  620. }
  621. // MARK: Filtering
  622. /**
  623. Returns a `Results` containing all objects matching the given predicate in the collection.
  624. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  625. */
  626. public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
  627. return base.filter(NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  628. }
  629. /**
  630. Returns a `Results` containing all objects matching the given predicate in the collection.
  631. - parameter predicate: The predicate with which to filter the objects.
  632. - returns: A `Results` containing objects that match the given predicate.
  633. */
  634. public func filter(_ predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) }
  635. // MARK: Sorting
  636. /**
  637. Returns a `Results` containing the objects in the collection, but sorted.
  638. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
  639. youngest to oldest based on their `age` property, you might call
  640. `students.sorted(byKeyPath: "age", ascending: true)`.
  641. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  642. floating point, integer, and string types.
  643. - parameter keyPath: The key path to sort by.
  644. - parameter ascending: The direction to sort in.
  645. */
  646. public func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> {
  647. return base.sorted(byKeyPath: keyPath, ascending: ascending)
  648. }
  649. /**
  650. Returns a `Results` containing the objects in the collection, but sorted.
  651. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  652. floating point, integer, and string types.
  653. - see: `sorted(byKeyPath:ascending:)`
  654. - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
  655. */
  656. public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
  657. where S.Iterator.Element == SortDescriptor {
  658. return base.sorted(by: sortDescriptors)
  659. }
  660. // MARK: Aggregate Operations
  661. /**
  662. Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
  663. collection is empty.
  664. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  665. - parameter property: The name of a property whose minimum value is desired.
  666. */
  667. public func min<T: MinMaxType>(ofProperty property: String) -> T? {
  668. return base.min(ofProperty: property)
  669. }
  670. /**
  671. Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
  672. collection is empty.
  673. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  674. - parameter property: The name of a property whose minimum value is desired.
  675. */
  676. public func max<T: MinMaxType>(ofProperty property: String) -> T? {
  677. return base.max(ofProperty: property)
  678. }
  679. /**
  680. Returns the sum of the values of a given property over all the objects in the collection.
  681. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  682. - parameter property: The name of a property whose values should be summed.
  683. */
  684. public func sum<T: AddableType>(ofProperty property: String) -> T { return base.sum(ofProperty: property) }
  685. /**
  686. Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is
  687. empty.
  688. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
  689. - parameter property: The name of a property whose average value should be calculated.
  690. */
  691. public func average(ofProperty property: String) -> Double? { return base.average(ofProperty: property) }
  692. // MARK: Sequence Support
  693. /**
  694. Returns the object at the given `index`.
  695. - parameter index: The index.
  696. */
  697. public subscript(position: Int) -> Element { return base[position] }
  698. /// Returns a `RLMIterator` that yields successive elements in the collection.
  699. public func makeIterator() -> RLMIterator<Element> { return base.makeIterator() }
  700. // MARK: Collection Support
  701. /// The position of the first element in a non-empty collection.
  702. /// Identical to endIndex in an empty collection.
  703. public var startIndex: Int { return base.startIndex }
  704. /// The collection's "past the end" position.
  705. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
  706. /// zero or more applications of successor().
  707. public var endIndex: Int { return base.endIndex }
  708. // MARK: Key-Value Coding
  709. /**
  710. Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
  711. objects.
  712. - parameter key: The name of the property whose values are desired.
  713. */
  714. public func value(forKey key: String) -> Any? { return base.value(forKey: key) }
  715. /**
  716. Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
  717. collection's objects.
  718. - parameter keyPath: The key path to the property whose values are desired.
  719. */
  720. public func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
  721. /**
  722. Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
  723. - warning: This method may only be called during a write transaction.
  724. - parameter value: The value to set the property to.
  725. - parameter key: The name of the property whose value should be set on each object.
  726. */
  727. public func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
  728. // MARK: Notifications
  729. /**
  730. Registers a block to be called each time the collection changes.
  731. The block will be asynchronously called with the initial results, and then called again after each write
  732. transaction which changes either any of the objects in the collection, or which objects are in the collection.
  733. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
  734. the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
  735. documentation for more information on the change information supplied and an example of how to use it to update a
  736. `UITableView`.
  737. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
  738. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  739. perform blocking work.
  740. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
  741. other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
  742. single notification. This can include the notification with the initial collection.
  743. For example, the following code performs a write transaction immediately after adding the notification block, so
  744. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  745. will reflect the state of the Realm after the write transaction.
  746. ```swift
  747. let results = realm.objects(Dog.self)
  748. print("dogs.count: \(dogs?.count)") // => 0
  749. let token = dogs.observe { changes in
  750. switch changes {
  751. case .initial(let dogs):
  752. // Will print "dogs.count: 1"
  753. print("dogs.count: \(dogs.count)")
  754. break
  755. case .update:
  756. // Will not be hit in this example
  757. break
  758. case .error:
  759. break
  760. }
  761. }
  762. try! realm.write {
  763. let dog = Dog()
  764. dog.name = "Rex"
  765. person.dogs.append(dog)
  766. }
  767. // end of run loop execution context
  768. ```
  769. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  770. updates, call `invalidate()` on the token.
  771. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  772. - parameter block: The block to be called whenever a change occurs.
  773. - returns: A token which must be held for as long as you want updates to be delivered.
  774. */
  775. public func observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
  776. -> NotificationToken { return base._observe(block) }
  777. /// :nodoc:
  778. public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
  779. -> NotificationToken { return base._observe(block) }
  780. }
  781. // MARK: AssistedObjectiveCBridgeable
  782. private struct AnyRealmCollectionBridgingMetadata<T: RealmCollectionValue> {
  783. var baseMetadata: Any?
  784. var baseType: _AnyRealmCollectionBase<T>.Type
  785. }
  786. extension AnyRealmCollection: AssistedObjectiveCBridgeable {
  787. static func bridging(from objectiveCValue: Any, with metadata: Any?) -> AnyRealmCollection {
  788. guard let metadata = metadata as? AnyRealmCollectionBridgingMetadata<Element> else { preconditionFailure() }
  789. return AnyRealmCollection(base: metadata.baseType.bridging(from: objectiveCValue, with: metadata.baseMetadata))
  790. }
  791. var bridged: (objectiveCValue: Any, metadata: Any?) {
  792. return (
  793. objectiveCValue: base.bridged.objectiveCValue,
  794. metadata: AnyRealmCollectionBridgingMetadata(baseMetadata: base.bridged.metadata, baseType: type(of: base))
  795. )
  796. }
  797. }
  798. // MARK: Unavailable
  799. extension RealmCollection {
  800. @available(*, unavailable, renamed: "sorted(byKeyPath:ascending:)")
  801. func sorted(byProperty property: String, ascending: Bool) -> Results<Element> { fatalError() }
  802. @available(*, unavailable, renamed: "observe(_:)")
  803. public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken {
  804. fatalError()
  805. }
  806. }