Search code examples
swiftrealmrealm-list

How to give values ​to a Realm List <Double>?


How to give values ​​to a Realm List ? I've created a second class for Double values, but I don't know if it's okay to do that. I tried to do it like this but it gives me two errors:

Cannot find 'a' in scope

Cannot find 'b' in scope

import UIKit
import RealmSwift

class Man: Object {
    @Persisted var _id: String?
    @Persisted var date: Int64?
    @Persisted var values: List<Pressure?>
}

class Pressure: Object {
    @Persisted var a: Double?
    @Persisted var b: Double?
}

let realm = try! Realm.init()
let man = Man.init()

man._id = generateRandom(size: 20)
man.date = Date().timestamp
man.values = Pressure(value: [a: 2.47635, b: 8.82763])

Solution

  • There are quite a few issues with the code in the question. First, I will rename the classes for readability. Man and man look very similar so I renamed the Man class as ManClass and Pressure to PressureClass

    Here are a few things

    1) Don't do this

    let realm = try! Realm.init()
    

    do this (see Configure and Open a Realm)

    let realm = try! Realm()
    

    2) there is no generateRandom function

    man._id = generateRandom(size: 20)
    

    if you want to create a "random" id, it's typically done with a UUID or preferably an ObjectID

    @Persisted var asda = UUID().uuidString
    

    or

    @Persisted(primaryKey: true) var _id: ObjectId //YAY!
    

    When the object is instatiated, that property is populated which eliminates the need to populate it manually. e.g. you don't need this

    man._id = generateRandom(size: 20)
    

    3) There is no timestamp function, and the .date property is Date, not a timestamp

    man.date = Date()
    

    4) When assigning values to properties, the property names have to be within quotes; "a" and "b" for example. Also, this is not appending a value to a list, so this doesn't work

    man.values = Pressure(value: [a: 2.47635, b: 8.82763])
    

    This does

    man.values = PressureClass(value: ["a": 2.47635, "b": 8.82763])
    

    you can also do this

    let p = PressureClass()
    p.a = 2.4
    p.b = 8.8
    

    and then

    man.values.append(p) //add a single value to a `List`
    

    OR you can update the PressureClass with a convenience init instead of dealing with this ["a": 2.47635, "b": 8.82763]

    class PressureClass: Object {
        @Persisted(primaryKey: true) var _id: ObjectId
        @Persisted var a: Double?
        @Persisted var b: Double?
    
        convenience init(a: Double, b:Double) {
            self.init()
            self.a = a
            self.b = b
        }
    }
    

    and then go nuts adding values

    let x = PressureClass(a: 2.4, b: 8.8)
    let y = PressureClass(a: 1.5, b: 2.6)
    let z = PressureClass(a: 9.5, b: 6.2)
    
    man.values.append(objectsIn: [x, y, z]) //add multiple values to a `List`