Change property Double to List<Double> property in a migration


(Fily) #1

I currently have a Realm object with a property of Double and I would like to change it a List<Double>.

The app is already in production so I would need to append the existing Double values into the List

Here is what I’m doing that gets me an error.

Existing Object:

class Item:Object{
    @objc dynamic var itemName:String = "General"
    @objc dynamic var price:Double = 0
}

Modified Object:

class Item:Object{
    @objc dynamic var itemName:String = "General"
    let prices = List<Double>()
}

Migration:
Based on the documentation, the following migration should work, but I get an error.

/// Schema 1:
Realm.Configuration.defaultConfiguration = Realm.Configuration(
    schemaVersion: 1,
    migrationBlock: { migration, oldSchemaVersion in
        if (oldSchemaVersion < 1) {
            migration.enumerateObjects(ofType: Item.className()) { oldObject, newObject in
                 
                 let price = oldObject!["price"] as! Double
                 let prices = newObject!["prices"] as! List<Double>
                 prices.append(price)
        }
    }
})

Error.

Could not cast value of type ‘RealmSwift.List<RealmSwift.DynamicObject>’ (0x107923c48) to ‘RealmSwift.List<Swift.Double>’ (0x1079232f8).


(Fily) #2

Here is what I had to do to make it work.

Realm.Configuration.defaultConfiguration = Realm.Configuration(
    schemaVersion: 1,
    migrationBlock: { migration, oldSchemaVersion in
        if (oldSchemaVersion < 1) {
            migration.enumerateObjects(ofType: Item.className()) { oldObject, newObject in

                 let price = oldObject!["price"] as! Double
                 newObject["prices"] = [price]
        }
    }
})