Is it possible to use enums in RealmSwift?

妖精的绣舞 提交于 2020-01-23 07:12:39

问题


I want to do something like this:

enum WeekDay {
    case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

class Person: Object {

    dynamic var birthday: WeekDay? = .Monday
    dynamic var id: String? = nil
    dynamic var birthdayRaw: String? = nil

    override static func primaryKey() -> String? {
        return "id"
    }
}

But, I'm getting an error:

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

How can I solve this ? Thanks for any help.


回答1:


Realm doesn't have a direct way do it. Github issue.

But you can consider this trick

enum WeekDay: String {
    case Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}

class Person: Object {
    private var _day: WeekDay?
    var birthday: WeekDay? {
        get {
            if let resolTypeRaw = birthdayRaw  {
                _day = WeekDay(rawValue: resolTypeRaw)
                return _day
            }
            return .Sunday
        }
        set {
            birthdayRaw = newValue?.rawValue
            _day = newValue
        }
    }

    dynamic var id: String? = nil
    dynamic var birthdayRaw: String? = nil

    override static func primaryKey() -> String? {
        return "id"
    }
}



回答2:


As of Realm 3.x you can use Int-based enums (apparently, by side-effect).

As of Realm 4.1 you can use any RawRepresentable enum (Int, Float, String) by complying with the "RealmEnum" protocol. Details in the pull request



来源:https://stackoverflow.com/questions/37050604/is-it-possible-to-use-enums-in-realmswift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!