是否可以在RealmSwift中使用枚举?

时间:2016-05-05 12:27:14

标签: ios swift enums realm

我想做这样的事情:

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

但是,我收到了错误:

  

属性不能标记为动态,因为它的类型不能   在Objective-C中表示

我该如何解决这个问题?谢谢你的帮助。

2 个答案:

答案 0 :(得分:10)

Realm没有直接的方式去做。 Github issue.

但你可以考虑这个技巧

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

答案 1 :(得分:0)

从Realm 3.x开始,您可以使用基于Int的枚举(显然是有副作用的)。

从Realm 4.1开始,您可以通过遵守“ RealmEnum”协议来使用任何RawRepresentable枚举(Int,Float,String)。 Details in the pull request