未解包的可选类型的原始值

raw Value of optional type not unwrapped

我试图解开 func toDictionary() 中枚举类型的原始值,但出现错误。 我怎样才能解决这个问题?

enum ChatFeatureType: String {

  case tenants
  case leaseholders
  case residents
}

class Chat {

 var featureType: ChatFeatureType?

  init(featureType: ChatFeatureType? = nil 
     self.featureType = featureType
  }

   //download data from firebase
 init(dictionary : [String : Any]) {
      featureType = ChatFeatureType(rawValue: dictionary["featureType"] as! String)!
     }

  func toDictionary() -> [String : Any] {

     var someDict = [String : Any]()

 //  I get error  on the line below: Value of optional type 'ChatFeatureType?' not unwrapped; did you mean to use '!' or '?'?
       someDict["featureType"] = featureType.rawValue ?? "" 
    }

 }

由于 featureType 是可选的,因此您必须添加 ?! 作为错误提示

someDict["featureType"] = featureType?.rawValue ?? "" 

但请注意,当您从字典创建 Chat 的实例并且键不存在时,您的代码确实会崩溃,因为没有大小写 "".

实际上枚举的目的是值总是其中一种情况。如果您需要未指定的案例,请添加 noneunknown 或类似的。

这是一个安全版本

enum ChatFeatureType: String {
     case none, tenants, leaseholders, residents
}

class Chat {

   var featureType: ChatFeatureType

   init(featureType: ChatFeatureType = .none)
       self.featureType = featureType
   }

   //download data from firebase
   init(dictionary : [String : Any]) {
       featureType = ChatFeatureType(rawValue: dictionary["featureType"] as? String) ?? .none
   }

   func toDictionary() -> [String : Any] {

      var someDict = [String : Any]()
      someDict["featureType"] = featureType.rawValue
      return someDict
  }
}