Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment ID in Realm, Swift 3.0

After a lot of troubles, i finally got my code converted to Swift 3.0.

But it seems like my incrementID function isn't working anymore?

Any suggestions how i can fix this?

My incrementID and primaryKey function as they look right now.

override static func primaryKey() -> String? {
    return "id"
}

func incrementID() -> Int{
    let realm = try! Realm()
    let RetNext: NSArray = Array(realm.objects(Exercise.self).sorted(byProperty: "id")) as NSArray
    let last = RetNext.lastObject
    if RetNext.count > 0 {
        let valor = (last as AnyObject).value(forKey: "id") as? Int
        return valor! + 1
    } else {
        return 1
    }
}
like image 844
Grumme Avatar asked Sep 19 '16 17:09

Grumme


1 Answers

There's no need to use KVC here, or to create a sorted array just to get the max value. You can just do:

func incrementID() -> Int {
    let realm = try! Realm()
    return (realm.objects(Exercise.self).max(ofProperty: "id") as Int? ?? 0) + 1
}
like image 115
Thomas Goyne Avatar answered Nov 15 '22 06:11

Thomas Goyne