Note: I don't work with Realm, so I could be off-topic here... Don't hesitate to tell me.
We see that Realm()
throws an error, but since you're using try!
instead of using Do-Catch and error handling, you're left with just a crash instead of an error message.
Since you're asking in a comment "But how can I declare an app wise variable with a do/catch statement as it is not allowed at the top level?", I would just make the property an Optional and populate its content when the view/window/init loads.
At the root of the class:
let realm: Realm?
In viewDidLoad
, or init
, or any other method called at startup that will fit your needs:
do {
self.realm = try Realm()
} catch let error as NSError {
print(error.debugDescription)
// handle errors here
}
Then in your app, safely unwrap before usage:
if let realm = self.realm {
// do your work with `realm`
}
or even better, follow the "happy path" and use guard:
guard let realm = self.realm else { return }
// do your work with `realm`
If you don't want to have to handle unwrapping the Optional property everywhere, you can declare it as an implicitly unwrapped optional instead:
let realm: Realm!
But then in the init part you must not forget to stop the app execution if it's nil, before trying to access the value.
do {
self.realm = try Realm()
} catch let error as NSError {
print(error.debugDescription)
fatalError("Can't continue further, no Realm available")
}