如何让 RealmSwift 使用 Xcode 11?

How to get RealmSwift working with Xcode 11?

我一直在尝试使用 Realm(4.3.0 版)作为数据库选项 Xcode 11。凭借我的谷歌搜索技能,我无法找到我的问题的答案。我试过使用 Official Realm documentation 但他们做事的方式似乎不适用于 Xcode 11。基本代码:

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)")

}

我收到了一个绝对没有预料到的错误:

另外,当我尝试初始化并写入 Realm 时:

let realm = try! Realm()

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

我得到 "Expected declaration"

的错误

根据我的阅读,Realm 似乎是 iOS 的一个非常好的数据库选项,但是由于这些问题,我无法起床 运行。任何帮助将不胜感激。

让我们重新安排代码,使对象和函数位于正确的位置。

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)
       }

    }
}

赞@108g 评论: 我试图在 class 级别创建一个实例。所以我将创建、修改和打印移到 viewDidLoad() 方法中。然后我将我的测试 class 移动到一个新文件中。

所以有效的代码: ViewController.swift

import UIKit
import RealmSwift

class ViewController: UIViewController {

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

        let newTest = Prompt()
        newTest.text = "Text"

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


        let realm = try! Realm()

        try! realm.write {
            realm.add(newTest)
        }
    }
}

和RealmTest.swift(新文件)

import Foundation
import RealmSwift

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