solidcell solidcell - 2 months ago 6
Swift Question

How can you create Results after creating records?

I have a method that should return

Results
, either by successfully querying, or by creating the records if they don't exist.

Something like:

class MyObject: Object {
dynamic var token = ""

static let realm = try! Realm()

class func findOrCreate(token token: String) -> Results<MyObject> {
// either it's found ...
let tokenResults = realm.objects(MyObject.self).filter("token = '\(token)'")
if !tokenResults.isEmpty {
return tokenResults
}
// ... or it's created
let newObject = MyObject()
newObject.token = token
try! realm.write {
realm.add(newObject)
}
// However, the next line results in the following error:
// 'Results<_>' cannot be constructed because it has no accessible initializers
return Results(newObject)
}
}


Maybe I should just be returning
[MyObject]
from this method. Is there any benefit to trying to keep it as
Results
instead of
Array
? I guess I'd lose any benefit of postponed evaluation since I'm already using
isEmpty
within the method, correct?

Answer

Results is an auto-updating view into underlying data in a Realm, which is why you can't construct it directly. So instead of return Results(newObject), you should return tokenResults, which will contain your newly added object, again because Results is an auto-updating view.

Comments