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])
There are quite a few issues with the code in the question. First, I will rename the classes for readability.
Manandmanlook very similar so I renamed theManclass asManClassandPressuretoPressureClassHere are a few things
1) Don't do this
do this (see Configure and Open a Realm)
2) there is no generateRandom function
if you want to create a "random" id, it's typically done with a UUID or preferably an ObjectID
or
When the object is instatiated, that property is populated which eliminates the need to populate it manually. e.g. you don't need this
3) There is no timestamp function, and the
.dateproperty isDate, not a timestamp4) 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
This does
you can also do this
and then
OR you can update the PressureClass with a convenience init instead of dealing with this
["a": 2.47635, "b": 8.82763]and then go nuts adding values