Search code examples
swiftobjectmapperrealm

Accessing primitive types in RealmSwift


I am using ObjectMapper along with RealmSwift and my class looks like:

class Location: Object, Mappable {
    var Lat : Float = 0
    var Lng : Float = 0

    required convenience init?(_ map: Map) {
        self.init()
    }

    func mapping(map: Map) {
        Lat <- map["Lat"];
        Lng <- map["Lng"];
    }
}

This Location class is referenced in another class Vehicle.swift which is also a subclass of Realm Object

I am able to access the location of the vehicle using the line:

let location : Location = vehicle.VehicleLocation!

Printing the value of location gives me the output:

location is  Location {
    Lat = 49.24122;
    Lng = -123.1153;
}

I opened the realm database using the Realm browser and the values correspond with those in the database.

However when I try to to access the Lat and Lng values, I am getting 0.0. I am trying to access these using :

let lat : Float = vehicle.VehicleLocation!.Lat
let lng : Float = vehicle.VehicleLocation!.Lng 

Any idea what might be happening ?


Solution

  • All stored Realm properties must be defined as dynamic.

    Change:

    var Lat : Float = 0
    var Lng : Float = 0
    

    To:

    dynamic var Lat : Float = 0
    dynamic var Lng : Float = 0