可选类型的原始值未解包

时间:2019-03-20 15:19:33

标签: swift3 enums

我正在尝试解开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 ?? "" 
    }

 }

1 个答案:

答案 0 :(得分:1)

由于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
  }
}