Search code examples
swiftrealm

How to Instantiate a Realm Results<T> Array


The Realm Swift documentation says that querying a Results<T> object returns an array, however, when I try to instantiate a Results array like this: var allObjects : Results<Object> = [], I get an error saying that I can't use Results with an array literal.

I know the Realm API Reference says that "Results instances cannot be directly instantiated;" but I was wondering if there is some kind of workaround to this.

I am wondering because I want to have a global variable that is instantiated with an empty array and is mutated in the viewWillAppear method of a UIViewController class. For example:

var allItems : Results<Item> = [] 

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let realm = try! Realm()
    self.allItems = realm.objects(Item.self).sorted(byKeyPath: "description")
}

Solution

  • Results is a type provided by Realm. Although on the outside it behaves like an array, it is actually an abstraction that encompasses Realm's lazy loading mechanism, which isn't exposed to end apps. As a result, it's not possible for third party apps to create new instances of Results.

    If you just want to hold onto an instance of Results created by a Realm query, you can make it an optional instead of trying to pre-emptively instantiate it.

    var allItems: Results<Item>?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let realm = try! Realm()
        self.allItems = realm.objects(Item.self).sorted(byKeyPath: "description")
    }