Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 779
Lorenzo Rossi Avatar asked Nov 16 '15 20:11

Lorenzo Rossi


People also ask

What is a Swift array?

Swift is a type inference language that is, it can automatically identify the data type of an array based on its values. Hence, we can create arrays without specifying the data type. For example, var numbers = [2, 4, 6, 8] print("Array: \(numbers)") // [2, 4, 6, 8]

Does realm work with SwiftUI?

Realm objects have bindings to SwiftUI controls and, much like toggling the bought property, they already start a realm transaction to write the changes in the database whenever you change those values.


1 Answers

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.

like image 200
bdash Avatar answered Oct 08 '22 07:10

bdash