问题
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