petegrif
petegrif

Reputation: 69

Why can't I set properties on a Realm Object?

I am just getting started with Realm so I was trying the simple example in the Realm documentation.

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

// create Dog object and set its properties
var myDog = Dog()
myDog.name = "Rex"
myDog.age = 5

print("name of dog: \(myDog.name)")
print("age of dog: \(myDog.age)")

// Get handle to default Realm
let realm = try! Realm()

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

But i'm getting the following build errors.

  1. Expected declaration (for the line myDog.name = "Rex"
  2. Consecutive declarations on a line must be seperated by ''' (for the line try! realm.write

Upvotes: 2

Views: 591

Answers (2)

Andres Gutierrez
Andres Gutierrez

Reputation: 1

I had the same problem following the documentation on their website. What worked for me was declaring the first instance of Realm in your appDelegate, in the function DidFinishLaunchingWithOptions.

Make sure you "Import RealmSwift" in the AppDelegate file as well.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    do {
        let realm = try Realm()
    }catch{
        print("Error initializing Realm")
    }
    return true

}

After this first initialization, you can init realm elsewhere with a simple:

let realm = try! Realm()

If there's any error initializing realm, that first init in appDelegate will catch it.

Upvotes: 0

TiM
TiM

Reputation: 15991

I'm getting the feeling that this problem is not about anything wrong in the code specifically, but more where the code is located when you're trying to build it.

Looking around at a few other Swift related issues on SO, the Expected declaration error usually occurs when you've written code logic in a class, but not properly inside a method. Depending on where you're trying to execute this code will probably dictate what's going on here.

Are you writing this code in a playground? Or an actual app project? If it's in an app, where are you trying to execute it?

Upvotes: 2

Related Questions