user2201063
user2201063

Reputation: 149

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!

Upvotes: 5

Views: 5954

Answers (2)

Matteo Crippa
Matteo Crippa

Reputation: 121

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
}

Upvotes: 6

user2201063
user2201063

Reputation: 149

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

Upvotes: 3

Related Questions