1 ////////////////////////////////////////////////////////////////////////////
3 // Copyright 2014 Realm Inc.
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
9 // http://www.apache.org/licenses/LICENSE-2.0
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.
17 ////////////////////////////////////////////////////////////////////////////
24 /// Internal class. Do not use directly.
25 public class ListBase: RLMListBase {
26 // Printable requires a description property defined in Swift (and not obj-c),
27 // and it has to be defined as override, which can't be done in a
29 /// Returns a human-readable description of the objects contained in the List.
30 @objc public override var description: String {
31 return descriptionWithMaxDepth(RLMDescriptionMaxDepth)
34 @objc private func descriptionWithMaxDepth(_ depth: UInt) -> String {
35 return RLMDescriptionWithMaxDepth("List", _rlmArray, depth)
38 /// Returns the number of objects in this List.
39 public var count: Int { return Int(_rlmArray.count) }
43 `List` is the container type in Realm used to define to-many relationships.
45 Like Swift's `Array`, `List` is a generic type that is parameterized on the type of `Object` it stores.
47 Unlike Swift's native collections, `List`s are reference types, and are only immutable if the Realm that manages them
48 is opened as read-only.
50 Lists can be filtered and sorted with the same predicates as `Results<Element>`.
52 Properties of `List` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`.
54 public final class List<Element: RealmCollectionValue>: ListBase {
58 /// The Realm which manages the list, or `nil` if the list is unmanaged.
59 public var realm: Realm? {
60 return _rlmArray.realm.map { Realm($0) }
63 /// Indicates if the list can no longer be accessed.
64 public var isInvalidated: Bool { return _rlmArray.isInvalidated }
68 /// Creates a `List` that holds Realm model objects of type `Element`.
69 public override init() {
70 super.init(array: Element._rlmArray())
73 internal init(rlmArray: RLMArray<AnyObject>) {
74 super.init(array: rlmArray)
77 // MARK: Index Retrieval
80 Returns the index of an object in the list, or `nil` if the object is not present.
82 - parameter object: An object to find.
84 public func index(of object: Element) -> Int? {
85 return notFoundToNil(index: _rlmArray.index(of: dynamicBridgeCast(fromSwift: object) as AnyObject))
89 Returns the index of the first object in the list matching the predicate, or `nil` if no objects match.
91 - parameter predicate: The predicate with which to filter the objects.
93 public func index(matching predicate: NSPredicate) -> Int? {
94 return notFoundToNil(index: _rlmArray.indexOfObject(with: predicate))
98 Returns the index of the first object in the list matching the predicate, or `nil` if no objects match.
100 - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
102 public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
103 return index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
106 // MARK: Object Retrieval
109 Returns the object at the given index (get), or replaces the object at the given index (set).
111 - warning: You can only set an object during a write transaction.
113 - parameter index: The index of the object to retrieve or replace.
115 public subscript(position: Int) -> Element {
117 throwForNegativeIndex(position)
118 return dynamicBridgeCast(fromObjectiveC: _rlmArray.object(at: UInt(position)))
121 throwForNegativeIndex(position)
122 _rlmArray.replaceObject(at: UInt(position), with: dynamicBridgeCast(fromSwift: newValue) as AnyObject)
126 /// Returns the first object in the list, or `nil` if the list is empty.
127 public var first: Element? { return _rlmArray.firstObject().map(dynamicBridgeCast) }
129 /// Returns the last object in the list, or `nil` if the list is empty.
130 public var last: Element? { return _rlmArray.lastObject().map(dynamicBridgeCast) }
135 Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's
138 @nonobjc public func value(forKey key: String) -> [AnyObject] {
139 return _rlmArray.value(forKeyPath: key)! as! [AnyObject]
143 Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the
144 collection's objects.
146 - parameter keyPath: The key path to the property whose values are desired.
148 @nonobjc public func value(forKeyPath keyPath: String) -> [AnyObject] {
149 return _rlmArray.value(forKeyPath: keyPath) as! [AnyObject]
153 Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
155 - warning: This method can only be called during a write transaction.
157 - parameter value: The object value.
158 - parameter key: The name of the property whose value should be set on each object.
160 public override func setValue(_ value: Any?, forKey key: String) {
161 return _rlmArray.setValue(value, forKeyPath: key)
167 Returns a `Results` containing all objects matching the given predicate in the list.
169 - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
171 public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
172 return Results<Element>(_rlmArray.objects(with: NSPredicate(format: predicateFormat,
173 argumentArray: unwrapOptionals(in: args))))
177 Returns a `Results` containing all objects matching the given predicate in the list.
179 - parameter predicate: The predicate with which to filter the objects.
181 public func filter(_ predicate: NSPredicate) -> Results<Element> {
182 return Results<Element>(_rlmArray.objects(with: predicate))
188 Returns a `Results` containing the objects in the list, but sorted.
190 Objects are sorted based on the values of the given key path. For example, to sort a list of `Student`s from
191 youngest to oldest based on their `age` property, you might call
192 `students.sorted(byKeyPath: "age", ascending: true)`.
194 - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
195 floating point, integer, and string types.
197 - parameter keyPath: The key path to sort by.
198 - parameter ascending: The direction to sort in.
200 public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> {
201 return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
205 Returns a `Results` containing the objects in the list, but sorted.
207 - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
208 floating point, integer, and string types.
210 - see: `sorted(byKeyPath:ascending:)`
212 public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
213 where S.Iterator.Element == SortDescriptor {
214 return Results<Element>(_rlmArray.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
217 // MARK: Aggregate Operations
220 Returns the minimum (lowest) value of the given property among all the objects in the list, or `nil` if the list is
223 - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
225 - parameter property: The name of a property whose minimum value is desired.
227 public func min<T: MinMaxType>(ofProperty property: String) -> T? {
228 return _rlmArray.min(ofProperty: property).map(dynamicBridgeCast)
232 Returns the maximum (highest) value of the given property among all the objects in the list, or `nil` if the list
235 - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
237 - parameter property: The name of a property whose maximum value is desired.
239 public func max<T: MinMaxType>(ofProperty property: String) -> T? {
240 return _rlmArray.max(ofProperty: property).map(dynamicBridgeCast)
244 Returns the sum of the values of a given property over all the objects in the list.
246 - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
248 - parameter property: The name of a property whose values should be summed.
250 public func sum<T: AddableType>(ofProperty property: String) -> T {
251 return dynamicBridgeCast(fromObjectiveC: _rlmArray.sum(ofProperty: property))
255 Returns the average value of a given property over all the objects in the list, or `nil` if the list is empty.
257 - warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
259 - parameter property: The name of a property whose average value should be calculated.
261 public func average(ofProperty property: String) -> Double? {
262 return _rlmArray.average(ofProperty: property).map(dynamicBridgeCast)
268 Appends the given object to the end of the list.
270 If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing
273 - warning: This method may only be called during a write transaction.
275 - parameter object: An object.
277 public func append(_ object: Element) {
278 _rlmArray.add(dynamicBridgeCast(fromSwift: object) as AnyObject)
282 Appends the objects in the given sequence to the end of the list.
284 - warning: This method may only be called during a write transaction.
286 public func append<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == Element {
288 _rlmArray.add(dynamicBridgeCast(fromSwift: obj) as AnyObject)
293 Inserts an object at the given index.
295 - warning: This method may only be called during a write transaction.
297 - warning: This method will throw an exception if called with an invalid index.
299 - parameter object: An object.
300 - parameter index: The index at which to insert the object.
302 public func insert(_ object: Element, at index: Int) {
303 throwForNegativeIndex(index)
304 _rlmArray.insert(dynamicBridgeCast(fromSwift: object) as AnyObject, at: UInt(index))
308 Removes an object at the given index. The object is not removed from the Realm that manages it.
310 - warning: This method may only be called during a write transaction.
312 - warning: This method will throw an exception if called with an invalid index.
314 - parameter index: The index at which to remove the object.
316 public func remove(at index: Int) {
317 throwForNegativeIndex(index)
318 _rlmArray.removeObject(at: UInt(index))
322 Removes all objects from the list. The objects are not removed from the Realm that manages them.
324 - warning: This method may only be called during a write transaction.
326 public func removeAll() {
327 _rlmArray.removeAllObjects()
331 Replaces an object at the given index with a new object.
333 - warning: This method may only be called during a write transaction.
335 - warning: This method will throw an exception if called with an invalid index.
337 - parameter index: The index of the object to be replaced.
338 - parameter object: An object.
340 public func replace(index: Int, object: Element) {
341 throwForNegativeIndex(index)
342 _rlmArray.replaceObject(at: UInt(index), with: dynamicBridgeCast(fromSwift: object) as AnyObject)
346 Moves the object at the given source index to the given destination index.
348 - warning: This method may only be called during a write transaction.
350 - warning: This method will throw an exception if called with invalid indices.
352 - parameter from: The index of the object to be moved.
353 - parameter to: index to which the object at `from` should be moved.
355 public func move(from: Int, to: Int) {
356 throwForNegativeIndex(from)
357 throwForNegativeIndex(to)
358 _rlmArray.moveObject(at: UInt(from), to: UInt(to))
362 Exchanges the objects in the list at given indices.
364 - warning: This method may only be called during a write transaction.
366 - warning: This method will throw an exception if called with invalid indices.
368 - parameter index1: The index of the object which should replace the object at index `index2`.
369 - parameter index2: The index of the object which should replace the object at index `index1`.
371 public func swapAt(_ index1: Int, _ index2: Int) {
372 throwForNegativeIndex(index1, parameterName: "index1")
373 throwForNegativeIndex(index2, parameterName: "index2")
374 _rlmArray.exchangeObject(at: UInt(index1), withObjectAt: UInt(index2))
377 // MARK: Notifications
380 Registers a block to be called each time the collection changes.
382 The block will be asynchronously called with the initial results, and then called again after each write
383 transaction which changes either any of the objects in the collection, or which objects are in the collection.
385 The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
386 the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
387 documentation for more information on the change information supplied and an example of how to use it to update a
390 At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
391 not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
392 perform blocking work.
394 Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
395 other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
396 single notification. This can include the notification with the initial collection.
398 For example, the following code performs a write transaction immediately after adding the notification block, so
399 there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
400 will reflect the state of the Realm after the write transaction.
403 let results = realm.objects(Dog.self)
404 print("dogs.count: \(dogs?.count)") // => 0
405 let token = dogs.observe { changes in
407 case .initial(let dogs):
408 // Will print "dogs.count: 1"
409 print("dogs.count: \(dogs.count)")
412 // Will not be hit in this example
421 person.dogs.append(dog)
423 // end of run loop execution context
426 You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
427 updates, call `invalidate()` on the token.
429 - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
431 - parameter block: The block to be called whenever a change occurs.
432 - returns: A token which must be held for as long as you want updates to be delivered.
434 public func observe(_ block: @escaping (RealmCollectionChange<List>) -> Void) -> NotificationToken {
435 return _rlmArray.addNotificationBlock { _, change, error in
436 block(RealmCollectionChange.fromObjc(value: self, change: change, error: error))
441 extension List where Element: MinMaxType {
443 Returns the minimum (lowest) value in the list, or `nil` if the list is empty.
445 public func min() -> Element? {
446 return _rlmArray.min(ofProperty: "self").map(dynamicBridgeCast)
450 Returns the maximum (highest) value in the list, or `nil` if the list is empty.
452 public func max() -> Element? {
453 return _rlmArray.max(ofProperty: "self").map(dynamicBridgeCast)
457 extension List where Element: AddableType {
459 Returns the sum of the values in the list.
461 public func sum() -> Element {
462 return sum(ofProperty: "self")
466 Returns the average of the values in the list, or `nil` if the list is empty.
468 public func average() -> Double? {
469 return average(ofProperty: "self")
473 extension List: RealmCollection {
474 /// The type of the objects stored within the list.
475 public typealias ElementType = Element
477 // MARK: Sequence Support
479 /// Returns a `RLMIterator` that yields successive elements in the `List`.
480 public func makeIterator() -> RLMIterator<Element> {
481 return RLMIterator(collection: _rlmArray)
485 Replace the given `subRange` of elements with `newElements`.
487 - parameter subrange: The range of elements to be replaced.
488 - parameter newElements: The new elements to be inserted into the List.
490 public func replaceSubrange<C: Collection>(_ subrange: Range<Int>, with newElements: C)
491 where C.Iterator.Element == Element {
492 for _ in subrange.lowerBound..<subrange.upperBound {
493 remove(at: subrange.lowerBound)
495 for x in newElements.reversed() {
496 insert(x, at: subrange.lowerBound)
500 // This should be inferred, but Xcode 8.1 is unable to
502 public typealias Indices = DefaultRandomAccessIndices<List>
504 /// The position of the first element in a non-empty collection.
505 /// Identical to endIndex in an empty collection.
506 public var startIndex: Int { return 0 }
508 /// The collection's "past the end" position.
509 /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
510 /// zero or more applications of successor().
511 public var endIndex: Int { return count }
513 public func index(after i: Int) -> Int { return i + 1 }
514 public func index(before i: Int) -> Int { return i - 1 }
517 public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken {
518 let anyCollection = AnyRealmCollection(self)
519 return _rlmArray.addNotificationBlock { _, change, error in
520 block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error))
526 // MARK: - MutableCollection conformance, range replaceable collection emulation
527 extension List: MutableCollection {
528 public typealias SubSequence = RandomAccessSlice<List>
531 Returns the objects at the given range (get), or replaces the objects at the
532 given range with new objects (set).
534 - warning: Objects may only be set during a write transaction.
536 - parameter index: The index of the object to retrieve or replace.
538 public subscript(bounds: Range<Int>) -> SubSequence {
540 return SubSequence(base: self, bounds: bounds)
543 replaceSubrange(bounds.lowerBound..<bounds.upperBound, with: newValue)
548 Removes the specified number of objects from the beginning of the list. The
549 objects are not removed from the Realm that manages them.
551 - warning: This method may only be called during a write transaction.
553 public func removeFirst(_ number: Int = 1) {
554 let count = Int(_rlmArray.count)
555 guard number <= count else {
556 throwRealmException("It is not possible to remove more objects (\(number)) from a list"
557 + " than it already contains (\(count)).")
560 for _ in 0..<number {
561 _rlmArray.removeObject(at: 0)
566 Removes the specified number of objects from the end of the list. The objects
567 are not removed from the Realm that manages them.
569 - warning: This method may only be called during a write transaction.
571 public func removeLast(_ number: Int = 1) {
572 let count = Int(_rlmArray.count)
573 guard number <= count else {
574 throwRealmException("It is not possible to remove more objects (\(number)) from a list"
575 + " than it already contains (\(count)).")
578 for _ in 0..<number {
579 _rlmArray.removeLastObject()
584 Inserts the items in the given collection into the list at the given position.
586 - warning: This method may only be called during a write transaction.
588 public func insert<C: Collection>(contentsOf newElements: C, at i: Int) where C.Iterator.Element == Element {
590 for item in newElements {
591 insert(item, at: currentIndex)
597 Removes objects from the list at the given range.
599 - warning: This method may only be called during a write transaction.
601 public func removeSubrange(_ bounds: Range<Int>) {
602 removeSubrange(bounds.lowerBound..<bounds.upperBound)
606 public func removeSubrange(_ bounds: ClosedRange<Int>) {
607 removeSubrange(bounds.lowerBound...bounds.upperBound)
611 public func removeSubrange(_ bounds: CountableRange<Int>) {
613 remove(at: bounds.lowerBound)
618 public func removeSubrange(_ bounds: CountableClosedRange<Int>) {
620 remove(at: bounds.lowerBound)
625 public func removeSubrange(_ bounds: DefaultRandomAccessIndices<List>) {
626 removeSubrange(bounds.startIndex..<bounds.endIndex)
630 public func replaceSubrange<C: Collection>(_ subrange: ClosedRange<Int>, with newElements: C)
631 where C.Iterator.Element == Element {
632 removeSubrange(subrange)
633 insert(contentsOf: newElements, at: subrange.lowerBound)
637 public func replaceSubrange<C: Collection>(_ subrange: CountableRange<Int>, with newElements: C)
638 where C.Iterator.Element == Element {
639 removeSubrange(subrange)
640 insert(contentsOf: newElements, at: subrange.lowerBound)
644 public func replaceSubrange<C: Collection>(_ subrange: CountableClosedRange<Int>, with newElements: C)
645 where C.Iterator.Element == Element {
646 removeSubrange(subrange)
647 insert(contentsOf: newElements, at: subrange.lowerBound)
651 public func replaceSubrange<C: Collection>(_ subrange: DefaultRandomAccessIndices<List>, with newElements: C)
652 where C.Iterator.Element == Element {
653 removeSubrange(subrange)
654 insert(contentsOf: newElements, at: subrange.startIndex)
658 // MARK: - RangeReplaceableCollection support
659 extension List: RangeReplaceableCollection {
661 Removes the last object in the list. The object is not removed from the Realm that manages it.
663 - warning: This method may only be called during a write transaction.
665 public func removeLast() {
666 guard _rlmArray.count > 0 else {
667 throwRealmException("It is not possible to remove an object from an empty list.")
670 _rlmArray.removeLastObject()
674 // These should not be necessary, but Swift 3.1's compiler fails to infer the `SubSequence`,
675 // and the standard library neglects to provide the default implementation of `subscript`
677 public typealias SubSequence = RangeReplaceableRandomAccessSlice<List>
680 public subscript(slice: Range<Int>) -> SubSequence {
681 return SubSequence(base: self, bounds: slice)
687 // MARK: - AssistedObjectiveCBridgeable
689 extension List: AssistedObjectiveCBridgeable {
690 internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> List {
691 guard let objectiveCValue = objectiveCValue as? RLMArray<AnyObject> else { preconditionFailure() }
692 return List(rlmArray: objectiveCValue)
695 internal var bridged: (objectiveCValue: Any, metadata: Any?) {
696 return (objectiveCValue: _rlmArray, metadata: nil)
699 // MARK: - Unavailable
702 @available(*, unavailable, renamed: "remove(at:)")
703 public func remove(objectAtIndex: Int) { fatalError() }