Possibly, you shouldn't define realm as a class property, but rather locally in a do-try-catch
closure where you perform some realm action (say, realm.write
).
Moreover, at the line of the error: if the statementlet realm = try! Realm
fails, you will hit an assert which will cause that the app to crash at runtime (thanks @marius).
Instead, consider using your calls to Realm()
in some class method, where you handle possible errors/asserts via the catch
closure.
func TryToWriteToRealm(myText: String) {
do {
let realm = try Realm()
try realm.write {
realm.add(myText)
}
} catch {
print("Error!")
// some error handling
}
}
Then call TryToWriteToRealm(...)
when you want to e.g. Write to your realm.
For details of the difference between try
, try?
and try!
, see e.g.