使用枚举作为Realm模型的属性 [英] Using enum as property of Realm model

查看:144
本文介绍了使用枚举作为Realm模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用枚举作为我的模型的属性吗?我现在有一个这样的类:

Is it possible to use an Enum as a property for my model? I currently have a class like this:

class Checkin: RLMObject {
  dynamic var id: Int = 0
  dynamic var kind: String = "checked_in"
  var kindEnum: Kind = .CheckedIn {
    willSet { self.kind = newValue.rawValue }
  }

  enum Kind: String {
    case CheckedIn = "checked_in"
    case EnRoute = "en_route"
    case DroppedOff = "dropped_off"
  }
  ....
}

它可以正常工作,但我想要能够拥有 kind 属性是Enum,并且在将对象保存到商店时,Realm会自动调用该属性的 .rawValue 。这是可能在领域还是有一个功能要求已经在那里吗?

It works okay, but I'd like to be able to have the kind property be the Enum and have Realm automatically call .rawValue on the property when it is saving an object to the store. Is this possible in Realm or is there a feature request already out there for it?

推荐答案

你应该覆盖你的 kindEnum 的setter和getter为这种情况:

You should override your kindEnum's setter and getter for this case:

enum Kind: String {
  case CheckedIn
  case EnRoute
  case DroppedOff
}

class Checkin: Object {
  dynamic var id = 0
  dynamic var kind = Kind.CheckedIn.rawValue
  var kindEnum: Kind {
    get {
      return Kind(rawValue: kind)!
    }
    set {
      kind = newValue.rawValue
    }
  }
}

这篇关于使用枚举作为Realm模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆