Search code examples
iosswifterror-handlingrealm

Why does Realm use try! in Swift?


Why Does Realm use try! so frequently? It seems like if you're certain your call won't fail then you should not design it to throw - no?

Here is an example, from the Swift page on realm.io:

// Get the default Realm
let realm = try! Realm()

or

// Persist your data easily
try! realm.write {
  realm.add(myDog)
}

To me this implies they will never fail so why have the constructor or write() throw?


Solution

  • If you're referring to the examples in the Realm Swift Docs, I suspect try! is used liberally for the sake of brevity. The user is given a quick and dirty overview of core concepts without too much mental overhead.

    You probably will encounter errors at some point in your journey using Realm. You'll notice later on in the docs, in the Realms > Error Handling section that a do-catch example is given.

    do {
      let realm = try Realm()
    } catch let error as NSError {
      // handle error
    }
    

    To me, it's implied that the code examples from the docs are not necessarily production-quality, and the user is encouraged to use the relevant error-handling features of Swift.