Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 622
Jason Leach Avatar asked Feb 13 '16 05:02

Jason Leach


People also ask

What is realm for Swift?

Realm Swift is an easy to use alternative to SQLite and Core Data that makes persisting, querying, and syncing data as simple as working directly with native Swift objects. Deploy a sample appView documentation.

Why use realm Swift?

Many applications use Realm Swift – from chart-topping apps in the App Store to the world’s smallest cloud-hosted, SwiftUI chat app. Learn how Realm helps teams build better apps, faster. “ Realm makes the data persistence layer so easy on iOS. We have a big advantage in terms of developer speed and general feature development.

What is the best way to handle errors in Swift?

This is the “do or die” approach for handling errors. It is not recommended to handle errors this way in Swift as you need to be 100% sure that the call is safe. Using try! means we do not care about the possible error cases at all. For instance, if the parseName () doesn’t throw an error everything works fine: Name is good.

What are optionals in Swift?

Optionals: Swift introduced optionals that handle the absence of a value simply by declaring if there is a value or not. An optional is a type on its own! Optional chaining: The chaining of multiple optionals into a statement.


1 Answers

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.

like image 58
caseynolan Avatar answered Oct 05 '22 18:10

caseynolan