我对 Swift 中的 enum
有疑问。
我这样声明我的枚举:
enum FirstEnum : CustomStringConvertible {
case VALUE1
case VALUE2
case VALUE3
var description: String {
switch self {
case .VALUE1:
return "First value"
case .VALUE2:
return "Second value"
case .VALUE3:
return "Third value"
}
}
func getFromCode(value:String) -> FirstEnum? {
switch value {
case "v1":
return FirstEnum.VALUE1
case "v2":
return FirstEnum.VALUE2
case "v3" :
return FirstEnum.VALUE3
}
}
我需要从字符串(如字典)中获取枚举,所以我希望这一行应该有效:
let foo = FirstEnum.getFromCode("v1")
但 XCode (7) 需要一个 FirstEnum
参数用于方法 getFromCode
而不是方法定义中声明的 String
,说:
Cannot convert value of type "String" to expected argument type "FirstEnum"
为什么会这样?...我做错了什么?
最佳答案
使用Failable Initializers for Enumerations
You can use a failable initializer to select an appropriate enumeration member based on one or more parameters. The initializer can then fail if the provided parameters do not match an appropriate enumeration member.
The example below defines an enumeration called TemperatureUnit, with three possible states (Kelvin, Celsius, and Fahrenheit). A failable initializer is used to find an appropriate enumeration member for a Character value representing a temperature symbol:
enum TemperatureUnit {
case Kelvin, Celsius, Fahrenheit
init?(symbol: Character) {
switch symbol {
case "K":
self = .Kelvin
case "C":
self = .Celsius
case "F":
self = .Fahrenheit
default:
return nil
}
}
}
关于ios - 从值中获取枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32591965/