Why does Realm use try! in Swift?

Jason Leach picture Jason Leach · Feb 13, 2016 · Viewed 11.6k times · Source

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?

Answer

caseynolan picture caseynolan · Feb 13, 2016

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.