Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm Swift Results get object at index

Tags:

swift

realm

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

I'm using Realm in Swift and I'm having trouble to get an object out of the Results at a certain index. I'm using it inside my UITableViewController. I'm making a 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 be able to do something like this:

let task = tasks!.objectAtIndex(1)

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

like image 455
Kevin van Mierlo Avatar asked Jun 20 '15 10:06

Kevin van Mierlo


1 Answers

Use standard indexing syntax to retrieve the value:

let task = tasks![1]

Since tasks is an optional, it could be nil. A safer way to write this would be to use optional binding with optional chaining:

if let task = tasks?[1] {
    // use task
}
like image 128
vacawama Avatar answered Oct 19 '22 07:10

vacawama