问题描述
有没有办法定义枚举,从 rawValue
初始化时将默认为某个值而不是失败?
Is there a way to define an enum, when initialized from rawValue
will default to some value instead of failing? Useful in cases where the value may be unexpected (i.e. server API errors)
推荐答案
你的意思是这样的吗?
enum ErrorCode: Int {
case NoErr = 0, Err1, Err2, LastErr, DefaultErr
init(value: Int) {
if (value > LastErr.rawValue) {
self = .DefaultErr
} else {
self = ErrorCode(rawValue: value)!
}
}
}
let error: ErrorCode = .LastErr
let anotherError: ErrorCode = ErrorCode(value: 99)
这是另一个变体:
enum ErrorCode: Int {
case NoErr = 0, Err1, Err2, LastErr
init?(value: Int) {
if (value > 3) {
return nil
} else {
self = ErrorCode(rawValue: value)!
}
}
}
let error: ErrorCode = .LastErr
let anotherError: ErrorCode? = ErrorCode(value: 99)
相当于:
enum ErrorCode: Int {
case NoErr = 0, Err1, Err2, LastErr
}
let anotherError: ErrorCode? = ErrorCode(rawValue: 99)
因为苹果文档说:
原始值初始化器是一个可用的初始化器,因为不是每个
原始值返回枚举成员。有关更多信息,请参阅
可用的初始化程序。
The raw value initializer is a failable initializer, because not every raw value will return an enumeration member. For more information, see Failable Initializers.
但是一般来说,如果要使用带有rawvalue的枚举,期望一个可选的,并将nil返回值视为在枚举定义之外的默认错误情况。这将是我的建议。
But in general, if you want to use enum with rawvalue, you should expect an optional and treat the nil returned value as a default error case outside the enum definition. That would be my recommendation.
这篇关于具有默认值的不可用的枚举初始值设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!