Search code examples
iosarraysswiftrealm

Realm Lists and Swift Arrays


I'd like to use Realm to persist data as it seems much easier to learn and use than Core Data.
Some aspects are however still unclear to me, one of them is the use of Realm Lists.

For example I now have something like this:

class Foo {
    var a: String
    var b: [Bar]
    var average: Double {
        return Double(b.reduce(0.0, combine: {$0 + $1.c})) / Double(b.count);
    }
    //...

}

class Bar {
    var c: Float
    var d: NSDate
    //...
}

As I understand, I need to use a Realm List over the Swift Array in order to make "to-many relationships".
In addition to computing the average (as in the code), I use the foo.b array to populate a tableview and in some for in loops. I also map it to other arrays and use its filter() function.

Now, should I only use the Realm List or should I map it to a native Swift Array and then use that instead (for performance and simplicity reasons)?


Solution

  • The general advice is that if you should avoid converting from List<T> to [T] unless it's necessary. There are two reasons for this:

    1. List<T> is a live view onto the data rather than a point-in-time snapshot.
    2. List<T> can avoid instantiating Ts for many computations.

    Live view

    List<T> instances provide a live view onto the data rather than a point-in-time snapshot. You can hand one to a view controller and its contents will update after other parts of your application update the objects it contains.

    Efficiency

    List<T>, and the methods it provides, can avoid materializing instances of T in many cases. For instance, you can filter a List using an NSPredicate and Realm does not need to create Swift objects in memory to do so. Another case would be the average computed property in your example. It could be written like so (assuming b is now a List<Bar>):

    var average: Double {
        return b.average("c") as Double?
    }
    

    This will compute an average over the underlying values in the Realm without materializing the Bar instances.