solidcell solidcell - 1 month ago 5x
Swift Question

How can you create Results after creating records?

I have a method that should return

, 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 {
// 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
from this method. Is there any benefit to trying to keep it as
instead of
? I guess I'd lose any benefit of postponed evaluation since I'm already using
within the method, correct?


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.