Realm Swift results get object by index

I couldn't find this anywhere, so I thought I'd ask here.

I am using Realm in Swift and I am having a hard time getting an object from Results

at a specific index. I am using it internally UITableViewController

. I am doing var at the beginning of the class:

var tasks:Results<Task>?

      

And then, to get it, I .objects(type: T.Type)

:

tasks = realm.objects(Task)

      

I was hoping to do something like this:

let task = tasks!.objectAtIndex(1)

      

Is this a limitation or is there another way to do it?

+3


source to share


1 answer


Use the standard indexing syntax to retrieve the value:

let task = tasks![1]

      



Since it tasks

is optional, it can be nil

. A safer way to write this would be to use optional binding with optional chaining:

if let task = tasks?[1] {
    // use task
}

      

+11


source







All Articles