Auto increment ID in Realm, Swift 3.0

After a lot of trouble, I finally got my code converted to Swift 3.0.

But it looks like my incrementID function no longer works?

Any suggestions how can I fix this?

My incrementID and primaryKey functions 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 } } 
+6
source share
1 answer

There is no need to use KVC or create a sorted array to get the maximum value. You can simply:

 func incrementID() -> Int { let realm = try! Realm() return (realm.objects(Exercise.self).max(ofProperty: "id") as Int? ?? 0) + 1 } 
+24
source

All Articles