Search code examples
iosswiftxcoderealm

How to get RealmSwift working with Xcode 11?


I've been trying to get started with Realm (version 4.3.0) as a database option with Xcode 11. With my Googling skills I could not get an answer for my problems. I've tried to use the Official Realm documentation but it appears that the way they do things is not working with Xcode 11. Basic code:

import UIKit
import RealmSwift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    class Test: Object {
        @objc dynamic var text = ""
        @objc dynamic var internalId = 0
    }

    let newTest = Test()
    newTest.text = "Text" // Errors happen here



    print("text: \(newTest.text)")

}

I get an errors that I definitely was not expecting:

  • Consecutive declarations on a line must be separated by ';'
  • Expected '(' in argument list of function declaration
  • Expected '{' in body of function declaration
  • Expected 'func' keyword in instance method declaration
  • Expected declaration
  • Invalid redeclaration of 'newTest()'

Also when I'm trying to initialize and write to Realm with:

let realm = try! Realm()

try! realm.write { // Error here
   realm.add(newTest)
}

I get the error of "Expected declaration"

From what I've read, Realm seems like a really nice database option for iOS, but with these problems, I cannot get up and running. Any help would be greatly appreciated.


Solution

  • Let's rearrange the code so the objects and functions are in their correct place.

    import UIKit
    import RealmSwift
    
    //this makes the class available throughout the app
    class Test: Object {
       @objc dynamic var text = ""
       @objc dynamic var internalId = 0
    }
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
    
           //create a new realm object in memory
           let newTest = Test()
           newTest.text = "Text"
    
           print("text: \(newTest.text)")
    
           //persist the object to realm
           let realm = try! Realm()
           try! realm.write {
              realm.add(newTest)
           }
    
           //or read objects
           let results = realm.objects(Test.self)
           for object in results {
              print(object.text)
           }
    
        }
    }