Realm and the Forced-Try Expression

Is `try! Realm()` safe?

Marat Saytakov
1 min readMar 21, 2018

Realm Database Swift examples uses let realm = try! Realm() to get the default Realm object, and then calls their methods or whatever.

Tom Swift & The Exceptions (performance)

There is a forced-try expression used instead of handling the exception that a normal try may throw. This, as like as forced unwrap of any Optional, would lead app to crash if there is an error produced. The Swift Programming Language book says:

“[In case of forced-try] If the expression throws an error, a runtime error is produced.”

Docs also uses that expession every time you want to use Realm. I tried to realize if this is basically ok to call it everywhere.

tl;dr: it is basically ok.

Explanation

It seems, Realm may throw an exception only one time while initialization from disk drive. All subsequent calls are calls to cache.

If you’re a geek and you’ve caught exception for the first call (or if you’re ok with hardly probable crash for the first time), you’ll never get crashed for any other call.

So, it is basically ok, although it does not sound so good.

--

--

No responses yet