Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift cannot convert value of type to expected argument in Realm

I'm trying to wrap my head around the Realm API in Swift which looks extremely promising. I'm trying some demo code in their documentation and I keep getting the same error. I have a Dog.swift file with the following:

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

In my main ViewController.swift, I have the following to create an instance of Dog and try to save it. The issue is that the realm.add line is not compiling because it "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)
    }
  }
}

Any help would be greatly appreciated. Thanks!

like image 899
user2201063 Avatar asked Oct 14 '15 02:10

user2201063


2 Answers

You should add import RealmSwift in your Dog.swift file, and then change it like this:

class Dog: Object {
    dynamic var name = ""
    dynamic var age = 0
}
like image 176
Matteo Crippa Avatar answered Oct 03 '22 03:10

Matteo Crippa


Import the RealmSwift framework in the Dog class instead of the Realm framework.

like image 30
user2201063 Avatar answered Oct 03 '22 02:10

user2201063