Search code examples
iosswiftenumsrealm

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


so I have custom data type like below:

enum WeightUnit : String {
    case Piece
    case Gram
    case Kilogram
    case Karton
    case Pouch
    case Dus
    case Renteng
    case Botol

    init (weightUnitFromServer: String) {
        switch weightUnitFromServer {
            case "Pcs": self = .Piece
            case "Gram": self = .Gram
            case "Kilogram": self = .Kilogram
            case "Ctn": self = .Karton
            case "Pch": self = .Pouch
            case "Dus": self = .Dus
            case "Rtg": self = .Renteng
            case "Btl": self = .Botol
            default: self = .Piece
        }
    }


}

and I want my Product (realm object) has property of that WightUnit like this

class Product : Object {

    @objc dynamic var productID : Int = 0
    @objc dynamic var name : String = ""
    @objc dynamic var categoryID : Int = 0
    @objc dynamic var categoryName : String = ""
    @objc dynamic var unitPrice: Double = 0.0
    @objc dynamic var quantityInCart = 0
    @objc dynamic var quantityFromServer = 0
    @objc dynamic var descriptionProduct : String = ""
    @objc dynamic var hasBeenAddedToWishList : Bool = false
    @objc dynamic var hasBeenAddedToCart : Bool = false
    @objc dynamic var isNewProduct : Bool = false
    @objc dynamic var productWeight : String = ""
    @objc dynamic var weightUnit : WeightUnit?  <--- the problem in here
    @objc dynamic var minimumOrderQuantity = 0
    @objc dynamic var maximumOrderQuantity = 0
}

and it give an error :

Property cannot be marked @objc because its type cannot be represented in Objective-C

enter image description here

so can I make a realm object property from an enum ? how to do that if that possible?


Solution

  • 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
    }