Using Enum as Property of Realm Model

Using enum as property of Realm model

You should override your kindEnum's setter and getter for this case:

enum Kind: String {
case CheckedIn
case EnRoute
case DroppedOff
}

class Checkin: Object {
@objc dynamic var id = 0
var kind = Kind.CheckedIn.rawValue
var kindEnum: Kind {
get {
return Kind(rawValue: kind)!
}
set {
kind = newValue.rawValue
}
}
}

Can I make a property of Realm Object from Enum data type?

The way I do this is that I store the object as a String and then have a separate get only variable or method that converts the string to enum like this

class Animal: Object {
@objc dynamic var animalClass: String = ""

var animalClassType: AnimalClass? { return Class(rawValue: self.animalClass) }
}

enum AnimalClass: String {
case mammal, reptile
}

How to initially set the value in realm model property by [String] and call it to display?

There are no arrays in Realm. Realm uses Collections such as Results and Lists which have some similar functions to arrays but they are not the same

In this use case you should probably define names as a List

class Dog: Object {
@Persisted var names = List<String>()
}

and then once the Dog object is instantiated, populate the names property

let d = Dog()
d.names.append(objectsIn: ["Bob", "Charlie", "Puppy"])

This syntax @objc dynamic is older and while is still valid, please move to the more current syntax of @Persisted

RealmSwift with enum list

Realm's List can only store elements that are either Object subclasses or one of the supported property types of Realm (such as Int, String, etc.). Realm doesn't support storing enum values, so you cannot store them in a List either.

One alternative is to store the rawValue of your enum, since it has a rawValue of type String, which can be stored in Realm.



Related Topics



Leave a reply



Submit