How to extract an array of variables from objects saved in RealmSwift

Asked 2 years ago, Updated 2 years ago, 115 views

We are currently using RealmSwift to store data.
Several types of data are stored in one object, as shown below.

 class Sample: Object {
    dynamic var number —CGFloat=0
    dynamic var string: String=""
}

At this time,

 var floatArr: CGFloat = [ ]

As long as there are only "number" objects in the CGFloat type array as described above.
Is that possible?

I couldn't find a site that might be helpful, so
I am trying to implement it while looking at the official website.
It's hard to implement.

swift realm

2022-09-30 21:13

1 Answers

For Results, you can use valueForKey(_:) or valueForKeypath(_:) to extract only a specific set of properties.

let numbers=realm
    .objects (Sample.self)
    .valueForKey ("number")

The numbers type is NSArray, so you need a cast to treat it as an array of CGFloat.

 iflet numbers=number as?[CGFloat]{
    ...
}

Another solution is to use map().

let numbers=realm
    .objects (Sample.self)
    .map {$0.number}

If you want to add up or average what you want to do in the end, you can use the sum() or average() methods directly without bothering to array them.

By the way, CGFloat is not recommended as a data type to store in Realm because it varies from device to device (32-bit or 64-bit).For example, if you change from a 32-bit device to a 64-bit device and restore the data, the data type is different, so migration is required.Use Double (or Float).


2022-09-30 21:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.