我想做这样的事情:
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 表示
我该如何解决这个问题?感谢您的帮助。
Realm 没有直接的方法来做到这一点。 Github 问题。
但是你可以考虑这个技巧
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"
}
}
从 Realm 3.x 开始,您可以使用基于 Int 的枚举(显然,有副作用)。
从 Realm 4.1 开始,您可以通过遵守“RealmEnum”协议来使用任何 RawRepresentable 枚举(Int、Float、String)。 拉取请求中的详细信息
我创建了一个扩展,希望对您有帮助
import RealmSwift
protocol RealmPersistableEnum: RawRepresentable, _OptionalPersistable { }
extension RealmPersistableEnum where RawValue: _OptionalPersistable {
static func _rlmGetProperty(_ obj: ObjectBase, _ key: PropertyKey) -> Self {
Self(rawValue: RawValue._rlmGetProperty(obj, key)) ?? Self()
}
static func _rlmGetPropertyOptional(_ obj: ObjectBase, _ key: PropertyKey) -> Self? {
guard let value = RawValue._rlmGetPropertyOptional(obj, key) else { return nil }
return Self(rawValue: value)
}
static func _rlmSetProperty(_ obj: ObjectBase, _ key: PropertyKey, _ value: Self) {
RawValue._rlmSetProperty(obj, key, value.rawValue)
}
}
使用示例
enum SomeEnumInt: Int, RealmPersistableEnum {
case none = 0
case test = 1
case debug = 2
init() {
self = .none
}
}
enum SomeEnumString: String, RealmPersistableEnum {
case none
case test
case debug
init() {
self = .none
}
}
class Foo: Object {
@Persisted var v1: String
@Persisted var v2: SomeEnumInt
@Persisted var v3: SomeEnumString
}
enum QuestIcon: String, RawRepresentable, CaseIterable {
case tray = "tray.2.fill"
case charBook = "character.book.closed.fill"
}
extension QuestIcon: PersistableEnum { } // THIS!!!!!!!