Search code examples
iosarraysswiftrealmobjectmapper

Nested array of double in realm (swift)


I have this JSON:

{
"location": {
  "position": {
    "type": "Point",
    "coordinates": [
      45.579553,
      11.751805
    ]
  }
}
}

Which belongs to another JSON object.

Trying to map it with Realm and ObjectMapper, I am findind difficulties mapping the coordinates property which is an array of double.

That's what reading the documentation and S.O. seems to have sense:

import Foundation
import RealmSwift
import ObjectMapper


class Coordinate:Object, Mappable{

dynamic var latitude:Double = 0.0
dynamic var longitude:Double = 0.0

required convenience init?(_ map: Map) {
    self.init()
}
func mapping(map: Map) {
    latitude <- map[""]
    longitude <- map[""]

}


}

class Position: Object, Mappable{

var type:String = ""
var coordinates:Coordinate?

required convenience init?(_ map: Map) {
    self.init()
}
func mapping(map: Map) {
    type <- map["type"]
    coordinates <- map["coordinates"]

}

}

class Location: Object, Mappable{

dynamic var id = ""
dynamic var position:Position?
dynamic var desc = ""

override static func indexedProperties()->[String]{
    return["id"]
}

override class func primaryKey() -> String? {
    return "id"
}


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

func mapping(map: Map) {
    id <- map["id"]
    position <- map["position"]

}
}

However I'm stuck in understanding how to map the "coordinates" object. Please note that this problem has nothing to do with ObjectMapper itself, it's more of a question on how to assign an array of Double to a property in a Realm model.


Solution

  • I was able to solve this following the indications in this issue:

    https://github.com/realm/realm-cocoa/issues/1120 (credits @jazz-mobility)

    class DoubleObject:Object{
    
        dynamic var value:Double = 0.0
    
    }
    
    class Position: Object, Mappable{
    
        var type:String = ""
        var coordinates = List<DoubleObject>()
    
        required convenience init?(_ map: Map) {
            self.init()
        }
    
        func mapping(map: Map) {
            type <- map["type"]
    
            var coordinates:[Double]? = nil
            coordinates <- map["coordinates"]
    
    
            coordinates?.forEach { coordinate in
                let c = DoubleObject()
                c.value = coordinate
                self.coordinates.append(c)
            }
    
        }
    
    }