Instantiating Realm database for Swift 2.0 - best practice?

后端 未结 2 1643
面向向阳花
面向向阳花 2021-01-04 09:38

I\'m wondering what the best practice for instantiating a Realm database is for Swift 2. One of the major differences between Realm for Swift 1.2 and Swift 2 is that the Rea

相关标签:
2条回答
  • 2021-01-04 10:02

    Unless you're actually going to handle the errors you receive, I highly recommend using try!.

    Your second code snippet doesn't work because, if initializing the Realm fails, that realm variable is never assigned to, which is invalid. You could probably work around that by making the realm variable be of type Realm?.

    0 讨论(0)
  • 2021-01-04 10:05

    Keep in mind that both Realm() and write can throw. That means both of them need try catch unless you use try!. Like this:

        do {
            let realm = try Realm()
    
            do {
                try realm.write {
                    realm.add(myObject_1)
                }
            } catch let error {
                print(error)
            }
    
        } catch let error{
    
            print(error)
        }
    
    0 讨论(0)
提交回复
热议问题