ios - 从值中获取枚举

标签 ios swift enums

我对 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/

相关文章:

java - 具有ManyToMany关系的JPA枚举实体

java - 为什么使用枚举而不是常量?在软件设计和可读性方面哪个更好

ios - 两个 CGPaths/UIBeziers 之间的补间/插值

ios - 使用 CFDataRef 将证书保存到钥匙串(keychain)

objective-c - Objective-c 中的自定义属性

ios - 你可以在 Objective C 中将函数存储在数组中吗?

ios - 如何识别移动光标上的链接属性范围

ios - Swift 3 协议(protocol)和委托(delegate)方法?

json - 字符串化 JSON 到 Swift 对象或 JSON 字典

java - 如何在 ColdFusion 中访问 Java Enum?