Dominik Sturm Dominik Sturm - 3 months ago 32x
Swift Question

Persist an Array of CLLocationCoordinate2D in Realm Database

I'm writing a location based application where i need to save an array of

in my Realm model. What would be the best way to do that? Should i define a new model object for coordinates and use
to save that array or is there a better to do that?


As you said it, the best approach would be creating your own models for storing coordinates. You can have class named Location that will be model for CLLocationCoordinate2D and other Realm objects can persist it using List<Location> or just Location.

Define Location class:

class Location: Object {
    dynamic var latitude = 0.0
    dynamic var longitude = 0.0

    /// Get only computed properties are ignored in Realm
    var coordinate: CLLocationCoordinate2D {
        return CLLocationCoordinate2D(
            latitude: latitude,
            longitude: longitude)

And object that persists them:

class SomeObject: Object {
    let coordinates = List<Location>()

And you will be able to access CLLocationCoordinate2D via coordinate property. For example: