RealmCollection.swift 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  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. @frozen 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. @frozen 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. case is Decimal128.Type: return RLMArray(objectType: .decimal128, optional: true)
  153. case is ObjectId.Type: return RLMArray(objectType: .objectId, optional: true)
  154. default: fatalError("Unsupported type for List: \(type)?")
  155. }
  156. }
  157. extension Optional: RealmCollectionValue where Wrapped: RealmCollectionValue {
  158. /// :nodoc:
  159. public static func _rlmArray() -> RLMArray<AnyObject> {
  160. return arrayType(Wrapped.self)
  161. }
  162. /// :nodoc:
  163. public static func _nilValue() -> Optional {
  164. return nil
  165. }
  166. }
  167. extension Int: RealmCollectionValue {}
  168. extension Int8: RealmCollectionValue {}
  169. extension Int16: RealmCollectionValue {}
  170. extension Int32: RealmCollectionValue {}
  171. extension Int64: RealmCollectionValue {}
  172. extension Float: RealmCollectionValue {
  173. /// :nodoc:
  174. public static func _rlmArray() -> RLMArray<AnyObject> {
  175. return RLMArray(objectType: .float, optional: false)
  176. }
  177. }
  178. extension Double: RealmCollectionValue {
  179. /// :nodoc:
  180. public static func _rlmArray() -> RLMArray<AnyObject> {
  181. return RLMArray(objectType: .double, optional: false)
  182. }
  183. }
  184. extension Bool: RealmCollectionValue {
  185. /// :nodoc:
  186. public static func _rlmArray() -> RLMArray<AnyObject> {
  187. return RLMArray(objectType: .bool, optional: false)
  188. }
  189. }
  190. extension String: RealmCollectionValue {
  191. /// :nodoc:
  192. public static func _rlmArray() -> RLMArray<AnyObject> {
  193. return RLMArray(objectType: .string, optional: false)
  194. }
  195. }
  196. extension Date: RealmCollectionValue {
  197. /// :nodoc:
  198. public static func _rlmArray() -> RLMArray<AnyObject> {
  199. return RLMArray(objectType: .date, optional: false)
  200. }
  201. }
  202. extension Data: RealmCollectionValue {
  203. /// :nodoc:
  204. public static func _rlmArray() -> RLMArray<AnyObject> {
  205. return RLMArray(objectType: .data, optional: false)
  206. }
  207. }
  208. extension Decimal128: RealmCollectionValue {
  209. /// :nodoc:
  210. public static func _rlmArray() -> RLMArray<AnyObject> {
  211. return RLMArray(objectType: .decimal128, optional: false)
  212. }
  213. }
  214. extension ObjectId: RealmCollectionValue {
  215. /// :nodoc:
  216. public static func _rlmArray() -> RLMArray<AnyObject> {
  217. return RLMArray(objectType: .objectId, optional: false)
  218. }
  219. }
  220. /// :nodoc:
  221. public protocol _RealmCollectionEnumerator {
  222. // swiftlint:disable:next identifier_name
  223. func _asNSFastEnumerator() -> Any
  224. }
  225. /// :nodoc:
  226. public protocol RealmCollectionBase: RandomAccessCollection, LazyCollectionProtocol, CustomStringConvertible, ThreadConfined where Element: RealmCollectionValue {
  227. // This typealias was needed with Swift 3.1. It no longer is, but remains
  228. // just in case someone was depending on it
  229. typealias ElementType = Element
  230. }
  231. /**
  232. A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon.
  233. */
  234. public protocol RealmCollection: RealmCollectionBase, _RealmCollectionEnumerator {
  235. // Must also conform to `AssistedObjectiveCBridgeable`
  236. // MARK: Properties
  237. /// The Realm which manages the collection, or `nil` for unmanaged collections.
  238. var realm: Realm? { get }
  239. /**
  240. Indicates if the collection can no longer be accessed.
  241. The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection.
  242. */
  243. var isInvalidated: Bool { get }
  244. /// The number of objects in the collection.
  245. var count: Int { get }
  246. /// A human-readable description of the objects contained in the collection.
  247. var description: String { get }
  248. // MARK: Index Retrieval
  249. /**
  250. Returns the index of an object in the collection, or `nil` if the object is not present.
  251. - parameter object: An object.
  252. */
  253. func index(of object: Element) -> Int?
  254. /**
  255. Returns the index of the first object matching the predicate, or `nil` if no objects match.
  256. - parameter predicate: The predicate to use to filter the objects.
  257. */
  258. func index(matching predicate: NSPredicate) -> Int?
  259. /**
  260. Returns the index of the first object matching the predicate, or `nil` if no objects match.
  261. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  262. */
  263. func index(matching predicateFormat: String, _ args: Any...) -> Int?
  264. // MARK: Filtering
  265. /**
  266. Returns a `Results` containing all objects matching the given predicate in the collection.
  267. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  268. */
  269. func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element>
  270. /**
  271. Returns a `Results` containing all objects matching the given predicate in the collection.
  272. - parameter predicate: The predicate to use to filter the objects.
  273. */
  274. func filter(_ predicate: NSPredicate) -> Results<Element>
  275. // MARK: Sorting
  276. /**
  277. Returns a `Results` containing the objects in the collection, but sorted.
  278. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
  279. youngest to oldest based on their `age` property, you might call
  280. `students.sorted(byKeyPath: "age", ascending: true)`.
  281. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  282. floating point, integer, and string types.
  283. - parameter keyPath: The key path to sort by.
  284. - parameter ascending: The direction to sort in.
  285. */
  286. func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element>
  287. /**
  288. Returns a `Results` containing the objects in the collection, but sorted.
  289. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  290. floating point, integer, and string types.
  291. - see: `sorted(byKeyPath:ascending:)`
  292. - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
  293. */
  294. func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor
  295. // MARK: Aggregate Operations
  296. /**
  297. Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
  298. collection is empty.
  299. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  300. - parameter property: The name of a property whose minimum value is desired.
  301. */
  302. func min<T: MinMaxType>(ofProperty property: String) -> T?
  303. /**
  304. Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
  305. collection is empty.
  306. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  307. - parameter property: The name of a property whose minimum value is desired.
  308. */
  309. func max<T: MinMaxType>(ofProperty property: String) -> T?
  310. /**
  311. Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty.
  312. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
  313. - parameter property: The name of a property conforming to `AddableType` to calculate sum on.
  314. */
  315. func sum<T: AddableType>(ofProperty property: String) -> T
  316. /**
  317. Returns the average value of a given property over all the objects in the collection, or `nil` if
  318. the collection is empty.
  319. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  320. - parameter property: The name of a property whose values should be summed.
  321. */
  322. func average<T: AddableType>(ofProperty property: String) -> T?
  323. // MARK: Key-Value Coding
  324. /**
  325. Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
  326. objects.
  327. - parameter key: The name of the property whose values are desired.
  328. */
  329. func value(forKey key: String) -> Any?
  330. /**
  331. Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
  332. collection's objects.
  333. - parameter keyPath: The key path to the property whose values are desired.
  334. */
  335. func value(forKeyPath keyPath: String) -> Any?
  336. /**
  337. Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
  338. - warning: This method may only be called during a write transaction.
  339. - parameter value: The object value.
  340. - parameter key: The name of the property whose value should be set on each object.
  341. */
  342. func setValue(_ value: Any?, forKey key: String)
  343. // MARK: Notifications
  344. /**
  345. Registers a block to be called each time the collection changes.
  346. The block will be asynchronously called with the initial results, and then called again after each write
  347. transaction which changes either any of the objects in the collection, or which objects are in the collection.
  348. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
  349. the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
  350. documentation for more information on the change information supplied and an example of how to use it to update a
  351. `UITableView`.
  352. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
  353. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  354. perform blocking work.
  355. If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
  356. run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
  357. notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
  358. This can include the notification with the initial collection.
  359. For example, the following code performs a write transaction immediately after adding the notification block, so
  360. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  361. will reflect the state of the Realm after the write transaction.
  362. ```swift
  363. let results = realm.objects(Dog.self)
  364. print("dogs.count: \(dogs?.count)") // => 0
  365. let token = dogs.observe { changes in
  366. switch changes {
  367. case .initial(let dogs):
  368. // Will print "dogs.count: 1"
  369. print("dogs.count: \(dogs.count)")
  370. break
  371. case .update:
  372. // Will not be hit in this example
  373. break
  374. case .error:
  375. break
  376. }
  377. }
  378. try! realm.write {
  379. let dog = Dog()
  380. dog.name = "Rex"
  381. person.dogs.append(dog)
  382. }
  383. // end of run loop execution context
  384. ```
  385. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  386. updates, call `invalidate()` on the token.
  387. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  388. - parameter queue: The serial dispatch queue to receive notification on. If
  389. `nil`, notifications are delivered to the current thread.
  390. - parameter block: The block to be called whenever a change occurs.
  391. - returns: A token which must be held for as long as you want updates to be delivered.
  392. */
  393. func observe(on queue: DispatchQueue?, _ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken
  394. /// :nodoc:
  395. // swiftlint:disable:next identifier_name
  396. func _observe(_ queue: DispatchQueue?, _ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken
  397. // MARK: Frozen Objects
  398. /// Returns if this collection is frozen
  399. var isFrozen: Bool { get }
  400. /**
  401. Returns a frozen (immutable) snapshot of this collection.
  402. The frozen copy is an immutable collection which contains the same data as this collection
  403. currently contains, but will not update when writes are made to the containing Realm. Unlike
  404. live collections, frozen collections can be accessed from any thread.
  405. - warning: This method cannot be called during a write transaction, or when the containing
  406. Realm is read-only.
  407. - warning: Holding onto a frozen collection for an extended period while performing write
  408. transaction on the Realm may result in the Realm file growing to large sizes. See
  409. `Realm.Configuration.maximumNumberOfActiveVersions` for more information.
  410. */
  411. func freeze() -> Self
  412. /**
  413. Returns a live (mutable) version of this frozen collection.
  414. This method resolves a reference to a live copy of the same frozen collection.
  415. If called on a live collection, will return itself.
  416. */
  417. func thaw() -> Self?
  418. }
  419. public extension RealmCollection {
  420. /**
  421. Returns the index of the first object matching the given predicate, or `nil` if no objects match.
  422. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  423. */
  424. func index(matching predicateFormat: String, _ args: Any...) -> Int? {
  425. return index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  426. }
  427. /**
  428. Returns a `Results` containing all objects matching the given predicate in the collection.
  429. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
  430. */
  431. func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
  432. return filter(NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
  433. }
  434. }
  435. /// :nodoc:
  436. public protocol OptionalProtocol {
  437. associatedtype Wrapped
  438. /// :nodoc:
  439. // swiftlint:disable:next identifier_name
  440. func _rlmInferWrappedType() -> Wrapped
  441. }
  442. extension Optional: OptionalProtocol {
  443. /// :nodoc:
  444. // swiftlint:disable:next identifier_name
  445. public func _rlmInferWrappedType() -> Wrapped { return self! }
  446. }
  447. public extension RealmCollection where Element: MinMaxType {
  448. /**
  449. Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
  450. */
  451. func min() -> Element? {
  452. return min(ofProperty: "self")
  453. }
  454. /**
  455. Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
  456. */
  457. func max() -> Element? {
  458. return max(ofProperty: "self")
  459. }
  460. }
  461. public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: MinMaxType {
  462. /**
  463. Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
  464. */
  465. func min() -> Element.Wrapped? {
  466. return min(ofProperty: "self")
  467. }
  468. /**
  469. Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
  470. */
  471. func max() -> Element.Wrapped? {
  472. return max(ofProperty: "self")
  473. }
  474. }
  475. public extension RealmCollection where Element: AddableType {
  476. /**
  477. Returns the sum of the values in the collection, or `nil` if the collection is empty.
  478. */
  479. func sum() -> Element {
  480. return sum(ofProperty: "self")
  481. }
  482. /**
  483. Returns the average of all of the values in the collection.
  484. */
  485. func average<T: AddableType>() -> T? {
  486. return average(ofProperty: "self")
  487. }
  488. }
  489. public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: AddableType {
  490. /**
  491. Returns the sum of the values in the collection, or `nil` if the collection is empty.
  492. */
  493. func sum() -> Element.Wrapped {
  494. return sum(ofProperty: "self")
  495. }
  496. /**
  497. Returns the average of all of the values in the collection.
  498. */
  499. func average<T: AddableType>() -> T? {
  500. return average(ofProperty: "self")
  501. }
  502. }
  503. public extension RealmCollection where Element: Comparable {
  504. /**
  505. Returns a `Results` containing the objects in the collection, but sorted.
  506. Objects are sorted based on their values. For example, to sort a collection of `Date`s from
  507. neweset to oldest based, you might call `dates.sorted(ascending: true)`.
  508. - parameter ascending: The direction to sort in.
  509. */
  510. func sorted(ascending: Bool = true) -> Results<Element> {
  511. return sorted(byKeyPath: "self", ascending: ascending)
  512. }
  513. }
  514. public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: Comparable {
  515. /**
  516. Returns a `Results` containing the objects in the collection, but sorted.
  517. Objects are sorted based on their values. For example, to sort a collection of `Date`s from
  518. neweset to oldest based, you might call `dates.sorted(ascending: true)`.
  519. - parameter ascending: The direction to sort in.
  520. */
  521. func sorted(ascending: Bool = true) -> Results<Element> {
  522. return sorted(byKeyPath: "self", ascending: ascending)
  523. }
  524. }
  525. private class _AnyRealmCollectionBase<T: RealmCollectionValue>: AssistedObjectiveCBridgeable {
  526. typealias Wrapper = AnyRealmCollection<Element>
  527. typealias Element = T
  528. var realm: Realm? { fatalError() }
  529. var isInvalidated: Bool { fatalError() }
  530. var count: Int { fatalError() }
  531. var description: String { fatalError() }
  532. func index(of object: Element) -> Int? { fatalError() }
  533. func index(matching predicate: NSPredicate) -> Int? { fatalError() }
  534. func filter(_ predicate: NSPredicate) -> Results<Element> { fatalError() }
  535. func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> { fatalError() }
  536. func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor {
  537. fatalError()
  538. }
  539. func min<T: MinMaxType>(ofProperty property: String) -> T? { fatalError() }
  540. func max<T: MinMaxType>(ofProperty property: String) -> T? { fatalError() }
  541. func sum<T: AddableType>(ofProperty property: String) -> T { fatalError() }
  542. func average<T: AddableType>(ofProperty property: String) -> T? { fatalError() }
  543. subscript(position: Int) -> Element { fatalError() }
  544. func makeIterator() -> RLMIterator<T> { fatalError() }
  545. var startIndex: Int { fatalError() }
  546. var endIndex: Int { fatalError() }
  547. func value(forKey key: String) -> Any? { fatalError() }
  548. func value(forKeyPath keyPath: String) -> Any? { fatalError() }
  549. func setValue(_ value: Any?, forKey key: String) { fatalError() }
  550. // swiftlint:disable:next identifier_name
  551. func _observe(_ queue: DispatchQueue?, _ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
  552. -> NotificationToken { fatalError() }
  553. class func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self { fatalError() }
  554. var bridged: (objectiveCValue: Any, metadata: Any?) { fatalError() }
  555. // swiftlint:disable:next identifier_name
  556. func _asNSFastEnumerator() -> Any { fatalError() }
  557. var isFrozen: Bool { fatalError() }
  558. func freeze() -> AnyRealmCollection<T> { fatalError() }
  559. func thaw() -> AnyRealmCollection<T> { fatalError() }
  560. }
  561. private final class _AnyRealmCollection<C: RealmCollection>: _AnyRealmCollectionBase<C.Element> {
  562. let base: C
  563. init(base: C) {
  564. self.base = base
  565. }
  566. // MARK: Properties
  567. override var realm: Realm? { return base.realm }
  568. override var isInvalidated: Bool { return base.isInvalidated }
  569. override var count: Int { return base.count }
  570. override var description: String { return base.description }
  571. // MARK: Index Retrieval
  572. override func index(of object: C.Element) -> Int? { return base.index(of: object) }
  573. override func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
  574. // MARK: Filtering
  575. override func filter(_ predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) }
  576. // MARK: Sorting
  577. override func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<C.Element> {
  578. return base.sorted(byKeyPath: keyPath, ascending: ascending)
  579. }
  580. override func sorted<S: Sequence>
  581. (by sortDescriptors: S) -> Results<C.Element> where S.Iterator.Element == SortDescriptor {
  582. return base.sorted(by: sortDescriptors)
  583. }
  584. // MARK: Aggregate Operations
  585. override func min<T: MinMaxType>(ofProperty property: String) -> T? {
  586. return base.min(ofProperty: property)
  587. }
  588. override func max<T: MinMaxType>(ofProperty property: String) -> T? {
  589. return base.max(ofProperty: property)
  590. }
  591. override func sum<T: AddableType>(ofProperty property: String) -> T {
  592. return base.sum(ofProperty: property)
  593. }
  594. override func average<T: AddableType>(ofProperty property: String) -> T? {
  595. return base.average(ofProperty: property)
  596. }
  597. // MARK: Sequence Support
  598. override subscript(position: Int) -> C.Element {
  599. return base[position as! C.Index]
  600. }
  601. override func makeIterator() -> RLMIterator<Element> {
  602. // FIXME: it should be possible to avoid this force-casting
  603. return base.makeIterator() as! RLMIterator<Element>
  604. }
  605. /// :nodoc:
  606. override func _asNSFastEnumerator() -> Any {
  607. return base._asNSFastEnumerator()
  608. }
  609. // MARK: Collection Support
  610. override var startIndex: Int {
  611. // FIXME: it should be possible to avoid this force-casting
  612. return base.startIndex as! Int
  613. }
  614. override var endIndex: Int {
  615. // FIXME: it should be possible to avoid this force-casting
  616. return base.endIndex as! Int
  617. }
  618. // MARK: Key-Value Coding
  619. override func value(forKey key: String) -> Any? { return base.value(forKey: key) }
  620. override func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
  621. override func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
  622. // MARK: Notifications
  623. /// :nodoc:
  624. override func _observe(_ queue: DispatchQueue?, _ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
  625. -> NotificationToken { return base._observe(queue, block) }
  626. // MARK: AssistedObjectiveCBridgeable
  627. override class func bridging(from objectiveCValue: Any, with metadata: Any?) -> _AnyRealmCollection {
  628. return _AnyRealmCollection(
  629. base: (C.self as! AssistedObjectiveCBridgeable.Type).bridging(from: objectiveCValue, with: metadata) as! C)
  630. }
  631. override var bridged: (objectiveCValue: Any, metadata: Any?) {
  632. return (base as! AssistedObjectiveCBridgeable).bridged
  633. }
  634. override var isFrozen: Bool {
  635. return base.isFrozen
  636. }
  637. override func freeze() -> AnyRealmCollection<Element> {
  638. return AnyRealmCollection(base.freeze())
  639. }
  640. override func thaw() -> AnyRealmCollection<Element> {
  641. return AnyRealmCollection(base.thaw()!)
  642. }
  643. }
  644. /**
  645. A type-erased `RealmCollection`.
  646. Instances of `RealmCollection` forward operations to an opaque underlying collection having the same `Element` type.
  647. */
  648. public struct AnyRealmCollection<Element: RealmCollectionValue>: RealmCollection {
  649. /// The type of the objects contained within the collection.
  650. public typealias ElementType = Element
  651. public func index(after i: Int) -> Int { return i + 1 }
  652. public func index(before i: Int) -> Int { return i - 1 }
  653. /// The type of the objects contained in the collection.
  654. fileprivate let base: _AnyRealmCollectionBase<Element>
  655. fileprivate init(base: _AnyRealmCollectionBase<Element>) {
  656. self.base = base
  657. }
  658. /// Creates an `AnyRealmCollection` wrapping `base`.
  659. public init<C: RealmCollection>(_ base: C) where C.Element == Element {
  660. self.base = _AnyRealmCollection(base: base)
  661. }
  662. // MARK: Properties
  663. /// The Realm which manages the collection, or `nil` if the collection is unmanaged.
  664. public var realm: Realm? { return base.realm }
  665. /**
  666. Indicates if the collection can no longer be accessed.
  667. The collection can no longer be accessed if `invalidate()` is called on the containing `realm`.
  668. */
  669. public var isInvalidated: Bool { return base.isInvalidated }
  670. /// The number of objects in the collection.
  671. public var count: Int { return base.count }
  672. /// A human-readable description of the objects contained in the collection.
  673. public var description: String { return base.description }
  674. // MARK: Index Retrieval
  675. /**
  676. Returns the index of the given object, or `nil` if the object is not in the collection.
  677. - parameter object: An object.
  678. */
  679. public func index(of object: Element) -> Int? { return base.index(of: object) }
  680. /**
  681. Returns the index of the first object matching the given predicate, or `nil` if no objects match.
  682. - parameter predicate: The predicate with which to filter the objects.
  683. */
  684. public func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
  685. // MARK: Filtering
  686. /**
  687. Returns a `Results` containing all objects matching the given predicate in the collection.
  688. - parameter predicate: The predicate with which to filter the objects.
  689. - returns: A `Results` containing objects that match the given predicate.
  690. */
  691. public func filter(_ predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) }
  692. // MARK: Sorting
  693. /**
  694. Returns a `Results` containing the objects in the collection, but sorted.
  695. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
  696. youngest to oldest based on their `age` property, you might call
  697. `students.sorted(byKeyPath: "age", ascending: true)`.
  698. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  699. floating point, integer, and string types.
  700. - parameter keyPath: The key path to sort by.
  701. - parameter ascending: The direction to sort in.
  702. */
  703. public func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> {
  704. return base.sorted(byKeyPath: keyPath, ascending: ascending)
  705. }
  706. /**
  707. Returns a `Results` containing the objects in the collection, but sorted.
  708. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
  709. floating point, integer, and string types.
  710. - see: `sorted(byKeyPath:ascending:)`
  711. - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
  712. */
  713. public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
  714. where S.Iterator.Element == SortDescriptor {
  715. return base.sorted(by: sortDescriptors)
  716. }
  717. // MARK: Aggregate Operations
  718. /**
  719. Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
  720. collection is empty.
  721. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  722. - parameter property: The name of a property whose minimum value is desired.
  723. */
  724. public func min<T: MinMaxType>(ofProperty property: String) -> T? {
  725. return base.min(ofProperty: property)
  726. }
  727. /**
  728. Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
  729. collection is empty.
  730. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
  731. - parameter property: The name of a property whose minimum value is desired.
  732. */
  733. public func max<T: MinMaxType>(ofProperty property: String) -> T? {
  734. return base.max(ofProperty: property)
  735. }
  736. /**
  737. Returns the sum of the values of a given property over all the objects in the collection.
  738. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
  739. - parameter property: The name of a property whose values should be summed.
  740. */
  741. public func sum<T: AddableType>(ofProperty property: String) -> T { return base.sum(ofProperty: property) }
  742. /**
  743. Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is
  744. empty.
  745. - warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
  746. - parameter property: The name of a property whose average value should be calculated.
  747. */
  748. public func average<T: AddableType>(ofProperty property: String) -> T? { return base.average(ofProperty: property) }
  749. // MARK: Sequence Support
  750. /**
  751. Returns the object at the given `index`.
  752. - parameter index: The index.
  753. */
  754. public subscript(position: Int) -> Element { return base[position] }
  755. /// Returns a `RLMIterator` that yields successive elements in the collection.
  756. public func makeIterator() -> RLMIterator<Element> { return base.makeIterator() }
  757. /// :nodoc:
  758. // swiftlint:disable:next identifier_name
  759. public func _asNSFastEnumerator() -> Any { return base._asNSFastEnumerator() }
  760. // MARK: Collection Support
  761. /// The position of the first element in a non-empty collection.
  762. /// Identical to endIndex in an empty collection.
  763. public var startIndex: Int { return base.startIndex }
  764. /// The collection's "past the end" position.
  765. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
  766. /// zero or more applications of successor().
  767. public var endIndex: Int { return base.endIndex }
  768. // MARK: Key-Value Coding
  769. /**
  770. Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
  771. objects.
  772. - parameter key: The name of the property whose values are desired.
  773. */
  774. public func value(forKey key: String) -> Any? { return base.value(forKey: key) }
  775. /**
  776. Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
  777. collection's objects.
  778. - parameter keyPath: The key path to the property whose values are desired.
  779. */
  780. public func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
  781. /**
  782. Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
  783. - warning: This method may only be called during a write transaction.
  784. - parameter value: The value to set the property to.
  785. - parameter key: The name of the property whose value should be set on each object.
  786. */
  787. public func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
  788. // MARK: Notifications
  789. /**
  790. Registers a block to be called each time the collection changes.
  791. The block will be asynchronously called with the initial results, and then called again after each write
  792. transaction which changes either any of the objects in the collection, or which objects are in the collection.
  793. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
  794. the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
  795. documentation for more information on the change information supplied and an example of how to use it to update a
  796. `UITableView`.
  797. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
  798. not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
  799. perform blocking work.
  800. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
  801. other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
  802. single notification. This can include the notification with the initial collection.
  803. For example, the following code performs a write transaction immediately after adding the notification block, so
  804. there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
  805. will reflect the state of the Realm after the write transaction.
  806. ```swift
  807. let results = realm.objects(Dog.self)
  808. print("dogs.count: \(dogs?.count)") // => 0
  809. let token = dogs.observe { changes in
  810. switch changes {
  811. case .initial(let dogs):
  812. // Will print "dogs.count: 1"
  813. print("dogs.count: \(dogs.count)")
  814. break
  815. case .update:
  816. // Will not be hit in this example
  817. break
  818. case .error:
  819. break
  820. }
  821. }
  822. try! realm.write {
  823. let dog = Dog()
  824. dog.name = "Rex"
  825. person.dogs.append(dog)
  826. }
  827. // end of run loop execution context
  828. ```
  829. You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
  830. updates, call `invalidate()` on the token.
  831. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
  832. - parameter block: The block to be called whenever a change occurs.
  833. - returns: A token which must be held for as long as you want updates to be delivered.
  834. */
  835. public func observe(on queue: DispatchQueue? = nil,
  836. _ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
  837. -> NotificationToken { return base._observe(queue, block) }
  838. /// :nodoc:
  839. // swiftlint:disable:next identifier_name
  840. public func _observe(_ queue: DispatchQueue?, _ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
  841. -> NotificationToken { return base._observe(queue, block) }
  842. // MARK: Frozen Objects
  843. /// Returns if this collection is frozen.
  844. public var isFrozen: Bool { return base.isFrozen }
  845. /**
  846. Returns a frozen (immutable) snapshot of this collection.
  847. The frozen copy is an immutable collection which contains the same data as this collection
  848. currently contains, but will not update when writes are made to the containing Realm. Unlike
  849. live collections, frozen collections can be accessed from any thread.
  850. - warning: This method cannot be called during a write transaction, or when the containing
  851. Realm is read-only.
  852. - warning: Holding onto a frozen collection for an extended period while performing write
  853. transaction on the Realm may result in the Realm file growing to large sizes. See
  854. `Realm.Configuration.maximumNumberOfActiveVersions` for more information.
  855. */
  856. public func freeze() -> AnyRealmCollection { return base.freeze() }
  857. /**
  858. Returns a live version of this frozen collection.
  859. This method resolves a reference to a live copy of the same frozen collection.
  860. If called on a live collection, will return itself.
  861. */
  862. public func thaw() -> AnyRealmCollection? { return base.thaw() }
  863. }
  864. // MARK: AssistedObjectiveCBridgeable
  865. private struct AnyRealmCollectionBridgingMetadata<T: RealmCollectionValue> {
  866. var baseMetadata: Any?
  867. var baseType: _AnyRealmCollectionBase<T>.Type
  868. }
  869. extension AnyRealmCollection: AssistedObjectiveCBridgeable {
  870. internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> AnyRealmCollection {
  871. guard let metadata = metadata as? AnyRealmCollectionBridgingMetadata<Element> else { preconditionFailure() }
  872. return AnyRealmCollection(base: metadata.baseType.bridging(from: objectiveCValue, with: metadata.baseMetadata))
  873. }
  874. internal var bridged: (objectiveCValue: Any, metadata: Any?) {
  875. return (
  876. objectiveCValue: base.bridged.objectiveCValue,
  877. metadata: AnyRealmCollectionBridgingMetadata(baseMetadata: base.bridged.metadata, baseType: type(of: base))
  878. )
  879. }
  880. }
  881. // MARK: Collection observation helpers
  882. internal protocol ObservableCollection: RealmCollection {
  883. associatedtype BackingObjcCollection
  884. func isSameObjcCollection(_ objc: BackingObjcCollection) -> Bool
  885. init(objc: BackingObjcCollection)
  886. }
  887. extension ObservableCollection {
  888. // We want to pass the same object instance to the change callback each time.
  889. // If the callback is being called on the source thread the instance should
  890. // be `self`, but if it's on a different thread it needs to be a new Swift
  891. // wrapper for the obj-c type, which we'll construct the first time the
  892. // callback is called.
  893. internal typealias ObjcCollectionChange = (BackingObjcCollection?, RLMCollectionChange?, Error?) -> Void
  894. internal func wrapObserveBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> ObjcCollectionChange {
  895. var anyCollection: AnyRealmCollection<Element>?
  896. return { collection, change, error in
  897. if anyCollection == nil, let collection = collection {
  898. anyCollection = AnyRealmCollection(self.isSameObjcCollection(collection) ? self : Self(objc: collection))
  899. }
  900. block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error))
  901. }
  902. }
  903. internal func wrapObserveBlock(_ block: @escaping (RealmCollectionChange<Self>) -> Void) -> ObjcCollectionChange {
  904. var list: Self?
  905. return { array, change, error in
  906. if list == nil, let array = array {
  907. list = self.isSameObjcCollection(array) ? self : Self(objc: array)
  908. }
  909. block(RealmCollectionChange.fromObjc(value: list, change: change, error: error))
  910. }
  911. }
  912. }
  913. extension List: ObservableCollection {
  914. internal typealias BackingObjcCollection = RLMArray<AnyObject>
  915. internal func isSameObjcCollection(_ rlmArray: BackingObjcCollection) -> Bool {
  916. return _rlmArray === rlmArray
  917. }
  918. }
  919. extension Results: ObservableCollection {
  920. internal typealias BackingObjcCollection = RLMResults<AnyObject>
  921. internal func isSameObjcCollection(_ objc: RLMResults<AnyObject>) -> Bool {
  922. return objc === rlmResults
  923. }
  924. }
  925. extension LinkingObjects: ObservableCollection {
  926. internal typealias BackingObjcCollection = RLMResults<AnyObject>
  927. internal func isSameObjcCollection(_ objc: RLMResults<AnyObject>) -> Bool {
  928. return objc === rlmResults
  929. }
  930. }