Swift3 未展开可选类型的原始值
我试图在Swift3 未展开可选类型的原始值,swift3,enums,Swift3,Enums,我试图在func toDictionary()中打开枚举类型的原始值,但出现错误。 我怎样才能解决这个问题 enum ChatFeatureType: String { case tenants case leaseholders case residents } class Chat { var featureType: ChatFeatureType? init(featureType: ChatFeatureType? = nil self.featu
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 ?? ""
但是请注意,当您从字典中创建聊天
实例时,代码会可靠地崩溃,并且密钥不存在,因为没有大小写“
”
实际上,枚举的目的是使值始终是其中一种情况。如果需要未指定的案例,请添加none
或unknown
或类似内容
这是一个安全的版本
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
}
}
现在我明白了。但是,即使我试图通过添加感叹号来强制展开,它仍然会输出相同的错误:someDict[“featureType”]=featureType.rawValue
您必须在featureType
之后添加感叹号,这是可选的(featureType!.rawValue
)。