Why does Realm use try! in Swift? Why does Realm use try! in Swift? swift swift

Why does Realm use try! in Swift?


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.


From the Realm Swift 2.1.0 guide in the Writes section:

Because write transactions could potentially fail like any other disk IO operations, both Realm.write() & Realm.commitWrite() are marked as throws so you can handle and recover from failures like running out of disk space. There are no other recoverable errors. For brevity, our code samples don’t handle these errors but you certainly should in your production applications.

Source: https://realm.io/docs/swift/latest/#writes


The way I deal with this issue is by creating a DatabaseManager class, that handles the unlikely event of realm throwing an error:

public class DatabaseManager {    static var realm: Realm {        get {            do {                let realm = try Realm()                return realm            }            catch {                NSLog("Could not access database: ", error)            }            return self.realm        }    }    public static func write(realm: Realm, writeClosure: () -> ()) {        do {            try realm.write {                writeClosure()            }        } catch {            NSLog("Could not write to database: ", error)        }    }}

Thanks to that solution the code looks much cleaner whenever I want to read from realm or write to db :)

DatabaseManager.write(realm: realm) {    let queryResult = self.realm.objects(Cookies.self).filter("cookieId == %@", cookieId)    let cookie = queryResult.first    cookie?.expirationDate = expirationDate as NSDate?}