Declaration

Parameters

Returns a Results containing the objects in the collection, but sorted.

Objects are sorted based on the values of the given key path. For example, to sort a collection of Students from
youngest to oldest based on their age property, you might call
students.sorted(byKeyPath: "age", ascending: true).

Warning

Collections may only be sorted by properties of boolean, Date, NSDate, single and double-precision
floating point, integer, and string types.

Parameters

The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.

The change parameter that is passed to the block reports, in the form of indices within the collection, 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.

At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call realm.refresh(), accessing it will never
perform blocking work.

Notifications are delivered via the standard run loop, and so can’t be delivered while 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 collection.

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.

letresults=realm.objects(Dog.self)print("dogs.count: \(dogs?.count)")// => 0lettoken=dogs.observe{changesinswitchchanges{case.initial(letdogs):// Will print "dogs.count: 1"print("dogs.count: \(dogs.count)")breakcase.update:// Will not be hit in this examplebreakcase.error:break}}try!realm.write{letdog=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 be sent to the block. To stop receiving
updates, call invalidate() on the token.

Warning

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