List

public final class List<T: Object>: ListBase

List is the container type in Realm used to define to-many relationships.

Like Swift’s Arrays, Lists are parameterized on a single Object subclass (T).

Lists can be filtered and sorted with the same predicates as Results<T>.

When added as a property on Object models, the property must be declared as let and cannot be dynamic.

  • The type of the elements contained within this list.

    Declaration

    Swift

    public typealias Element = T
  • Returns the object at the given index (get), or replaces the object at the given index (set).

    Warning

    You can only set an object during a write transaction.

    Declaration

    Swift

    public subscript(index: Int) -> T

    Parameters

    index

    The index of the object to retrieve or replace.

    Return Value

    The object at the given index.

  • The Realm which manages the list. Returns nil for unmanaged lists.

    Declaration

    Swift

    public var realm: Realm?
  • Indicates if the list can no longer be accessed.

    Declaration

    Swift

    public var invalidated: Bool { return _rlmArray.invalidated }
  • Returns the index of an object in the list.

    Declaration

    Swift

    public func indexOf(object: T) -> Int?

    Parameters

    object

    An object to find.

    Return Value

    The index of the object, or nil if the object is not in the list.

  • Returns the index of the first object in the list matching the predicate.

    Declaration

    Swift

    public func indexOf(predicate: NSPredicate) -> Int?

    Parameters

    predicate

    The predicate with which to filter the objects.

    Return Value

    The index of the first matching object, or nil if no objects match.

  • Returns the index of the first object in the list matching the predicate.

    Declaration

    Swift

    public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int?

    Parameters

    predicateFormat

    A predicate format string, optionally followed by a variable number of arguments.

    Return Value

    The index of the first matching object, or nil if no objects match.

  • Returns the first object in the list, or nil if the list is empty.

    Declaration

    Swift

    public var first: T? { return _rlmArray.firstObject() as! T? }
  • Returns the last object in the list, or nil if the list is empty.

    Declaration

    Swift

    public var last: T? { return _rlmArray.lastObject() as! T? }
  • Returns an Array containing the results of invoking valueForKey(_:) using key on each of the collection’s objects.

    Declaration

    Swift

    public override func valueForKey(key: String) -> AnyObject?

    Parameters

    key

    The name of the property.

    Return Value

    An Array containing the results.

  • Returns an Array containing the results of invoking valueForKeyPath(_:) using keyPath on each of the collection’s objects.

    Declaration

    Swift

    public override func valueForKeyPath(keyPath: String) -> AnyObject?

    Parameters

    keyPath

    The key path to the property.

    Return Value

    An Array containing the results.

  • Invokes setValue(_:forKey:) on each of the collection’s objects using the specified value and key.

    Warning

    This method can only be called during a write transaction.

    Declaration

    Swift

    public override func setValue(value: AnyObject?, forKey key: String)

    Parameters

    value

    The object value.

    key

    The name of the property.

  • Returns all objects matching the given predicate in the list.

    Declaration

    Swift

    public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T>

    Parameters

    predicateFormat

    A predicate format string; variable arguments are supported.

    Return Value

    A Results containing objects that match the predicate.

  • Returns all objects matching the given predicate in the list.

    Declaration

    Swift

    public func filter(predicate: NSPredicate) -> Results<T>

    Parameters

    predicate

    The predicate with which to filter the objects.

    Return Value

    A Results containing objects that match the predicate.

  • Returns a sorted Results from the list.

    Declaration

    Swift

    public func sorted(property: String, ascending: Bool = true) -> Results<T>

    Parameters

    property

    The property name to sort by.

    ascending

    The direction to sort by.

    Return Value

    A Results containing the list objects sorted by the specified property.

  • Returns a sorted Results from the list.

    Declaration

    Swift

    public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T>

    Parameters

    sortDescriptors

    An sequence of SortDescriptors to sort by.

    Return Value

    A Results containing the list objects sorted by the specified property.

  • Returns the minimum (lowest) value of the given property among all the objects in the list.

    Warning

    Only a property whose type conforms to the MinMaxType protocol can be specified.

    Declaration

    Swift

    public func min<U: MinMaxType>(property: String) -> U?

    Parameters

    property

    The name of a property whose minimum value is desired.

    Return Value

    The minimum value of the property, or nil if the list is empty.

  • Returns the maximum (highest) value of the given property among all the objects in the list.

    Warning

    Only a property whose type conforms to the MinMaxType protocol can be specified.

    Declaration

    Swift

    public func max<U: MinMaxType>(property: String) -> U?

    Parameters

    property

    The name of a property whose maximum value is desired.

    Return Value

    The maximum value of the property, or ’nil if the list is empty.

  • Returns the sum of the values of a given property over all the objects in the list.

    Warning

    Only a property whose type conforms to the AddableType protocol can be specified.

    Declaration

    Swift

    public func sum<U: AddableType>(property: String) -> U

    Parameters

    property

    The name of a property whose values should be summed.

    Return Value

    The sum of the given property.

  • Returns the average value of a given property over all the objects in the list.

    Warning

    Only a property whose type conforms to the AddableType protocol can be specified.

    Declaration

    Swift

    public func average<U: AddableType>(property: String) -> U?

    Parameters

    property

    The name of a property whose average value should be calculated.

    Return Value

    The average value of the given property.

  • Appends the given object to the end of the list.

    If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing the receiver.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func append(object: T)

    Parameters

    object

    An object.

  • Appends the objects in the given sequence to the end of the list.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func appendContentsOf<S: SequenceType where S.Generator.Element == T>(objects: S)

    Parameters

    objects

    A sequence of objects.

  • Inserts an object at the given index.

    Warning

    This method may only be called during a write transaction.

    Warning

    This method will throw an exception if called with an invalid index.

    Declaration

    Swift

    public func insert(object: T, atIndex index: Int)

    Parameters

    object

    An object.

    index

    The index at which to insert the object.

  • Removes an object at the given index. The object is not removed from the Realm that manages it.

    Warning

    This method may only be called during a write transaction.

    Warning

    This method will throw an exception if called with an invalid index.

    Declaration

    Swift

    public func removeAtIndex(index: Int)

    Parameters

    index

    The index at which to remove the object.

  • Removes the last object in the list. The object is not removed from the Realm that manages it.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func removeLast()
  • Removes all objects from the list. The objects are not removed from the Realm that manages them.

    Warning

    This method may only be called during a write transaction.

    Declaration

    Swift

    public func removeAll()
  • Replaces an object at the given index with a new object.

    Warning

    This method may only be called during a write transaction.

    Warning

    This method will throw an exception if called with an invalid index.

    Declaration

    Swift

    public func replace(index: Int, object: T)

    Parameters

    index

    The index of the object to be replaced.

    object

    An object.

  • Moves the object at the given source index to the given destination index.

    Warning

    This method may only be called during a write transaction.

    Warning

    This method will throw an exception if called with invalid indices.

    Declaration

    Swift

    public func move(from from: Int, to: Int) { // swiftlint:disable:this variable_name

    Parameters

    from

    The index of the object to be moved.

    to

    index to which the object at from should be moved.

  • Exchanges the objects in the list at given indices.

    Warning

    This method may only be called during a write transaction.

    Warning

    This method will throw an exception if called with invalid indices.

    Declaration

    Swift

    public func swap(index1: Int, _ index2: Int)

    Parameters

    index1

    The index of the object which should replace the object at index index2.

    index2

    The index of the object which should replace the object at index index1.

  • Registers a block to be called each time the list changes.

    The block will be asynchronously called with the initial list, and then called again after each write transaction which changes the list or any of the items in the list.

    The change parameter that is passed to the block reports, in the form of indices within the list, which of the objects were added, removed, or modified during each write transaction. See the RealmCollectionChange documentation for more information on the change information supplied and an example of how to use it to update a UITableView.

    The block is called on the same thread as it was added on, and can only be added on threads which are currently within a run loop. Unless you are specifically creating and running a run loop on a background thread, this will normally only be the main thread.

    Notifications can’t be delivered as long as the run loop is blocked by other activity. When notifications can’t be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial list. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction, and will not include change information.

    let person = realm.objects(Person).first!
    print("dogs.count: \(person.dogs.count)") // => 0
    let token = person.dogs.addNotificationBlock { (changes: RealmCollectionChange) in
        switch changes {
            case .Initial(let dogs):
                // Will print "dogs.count: 1"
                print("dogs.count: \(dogs.count)")
                break
            case .Update:
                // Will not be hit in this example
                break
            case .Error:
                break
        }
    }
    try! realm.write {
        let dog = Dog()
        dog.name = "Rex"
        person.dogs.append(dog)
    }
    // end of run loop execution context
    

    You must retain the returned token for as long as you want updates to continue to be sent to the block. To stop receiving updates, call stop() on the token.

    Warning

    This method cannot be called during a write transaction, or when the containing Realm is read-only.

    Warning

    This method may only be called on a managed list.

    Declaration

    Swift

    public func addNotificationBlock(block: (RealmCollectionChange<List>) -> ()) -> NotificationToken

    Parameters

    block

    The block to be called each time the list changes.

    Return Value

    A token which must be held for as long as you want updates to be delivered.

  • Returns a GeneratorOf<T> that yields successive elements in the list.

    Declaration

    Swift

    public func generate() -> RLMGenerator<T>
  • Replace the given subRange of elements with newElements.

    Declaration

    Swift

    public func replaceRange<C: CollectionType where C.Generator.Element == T>(subRange: Range<Int>,
                                                                                   with newElements: C)

    Parameters

    subRange

    The range of elements to be replaced.

    newElements

    The new elements to be inserted into the list.

  • The position of the first element in a non-empty collection. Identical to endIndex in an empty collection.

    Declaration

    Swift

    public var startIndex: Int { return 0 }
  • The collection’s past the end position. endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor().

    Declaration

    Swift

    public var endIndex: Int { return count }