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)?
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]
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.
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:
List<T>
is a live view onto the data rather than a point-in-time snapshot.List<T>
can avoid instantiating T
s for many computations.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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With