关于 ios:我可以从 Enum 数据类型中创建 Realm Object 的属性吗?

 2022-02-13 

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

所以我有如下自定义数据类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
        }
    }


}

并且我希望我的产品(领域对象)具有该 WightUnit 的属性,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
}

它给出了一个错误:

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

enter

1
2
3
4
5
6
7
8
9
class Animal: Object {
    @objc dynamic var animalClass: String =""

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

enum AnimalClass: String {
    case mammal, reptile
}