我可以从Enum数据类型制作Realm Object的属性吗?

时间:2019-01-08 02:46:24

标签: ios swift enums realm

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

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的属性

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
}

并给出错误消息:

  

无法将属性标记为@objc,因为无法表示其类型   在Objective-C中

enter image description here

那么我可以从枚举中创建领域对象属性吗?如果可能的话该怎么办?

1 个答案:

答案 0 :(得分:1)

我这样做的方法是,将对象存储为String,然后有一个单独的get only变量或方法,可以像这样将字符串转换为枚举

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

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

enum AnimalClass: String {
    case mammal, reptile
}