How to return a class with values while retrieving data with Realm? I am trying to use this code, but swift 3 not allowed:
static func getInfoById(id: String) -> DataInfo {
let scope = DataInfo ()
let realm = try! Realm()
scope = realm.objects(DataInfo.self).filter("IdInfo == %@", id)
return scope
}
Your code realm.objects(DataInfo.self).filter("IdInfo == %@", id)
returns a Results<DataInfo>
(a filtered collection of DataInfo), thus you're not really returning a DataInfo
object. You can call scope.first!
to get one DataInfo
from the results.
static func getInfoById(id: String) -> DataInfo {
let realm = try! Realm()
let scope = realm.objects(DataInfo.self).filter("IdInfo == %@", id)
return scope.first!
}
Although, I don't recommend force-unwrapping since there can be no items found, and force-unwrapping a nil value results in a crash. Thus you can return a DataInfo?
instead.
static func getInfoById(id: String) -> DataInfo? {
let realm = try! Realm()
let scope = realm.objects(DataInfo.self).filter("IdInfo == %@", id)
return scope.first
}
Alternatively, if you have explicitly stated in your Realm Object subclass that IdInfo
is your primary key, you can use realm.object(ofType: DataInfo.type, forPrimaryKey: id)
instead.
static func getInfoById(id: String) -> DataInfo? {
let realm = try! Realm()
return realm.object(ofType: DataInfo.self, forPrimaryKey: id)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With