Swift 无法将类型的值转换为 Realm 中的预期参数

Swift cannot convert value of type to expected argument in Realm

我正在努力思考 Swift 中的领域 API,这看起来非常有前途。我在他们的文档中尝试了一些演示代码,但我一直遇到同样的错误。 我有一个包含以下内容的 Dog.swift 文件:

import Foundation
class Dog {
    dynamic var name = ""
    dynamic var age = 0
}

在我的主 ViewController.swift 中,我有以下内容来创建 Dog 的实例并尝试保存它。问题是 realm.add 行没有编译,因为它 "Cannot convert value of type 'Dog' to expected argument type 'Object'"

import UIKit
import RealmSwift

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let myDog = Dog()
    myDog.name = "Rex"
    myDog.age = 10

    // Get the default Realm
    let realm = try! Realm()
    // You only need to do this once (per thread)

    // Add to the Realm inside a transaction
    realm.write {
        realm.add(myDog)
    }
  }
}

如有任何帮助,我们将不胜感激。谢谢!

在 Dog 中导入 RealmSwift 框架 class 而不是 Realm 框架。

您应该在 Dog.swift 文件中添加 import RealmSwift,然后像这样更改它:

class Dog: Object {
    dynamic var name = ""
    dynamic var age = 0
}