swift 再识枚举变量

时间:2021-01-15 19:13:57

// Use enum to create an enumeration. Like classes and all other named types, enumerations can have methods associated with them.

// swift 中enum 变化比较大,枚举看起来和类差不多,因为它可以拥有自己的方法了, enum的创建如下

enum Rank: Int {
    case Ace = 1
    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King
    func simpleDescription() -> String {
        switch self
        {
        case .Ace:
            return "ace"
        case .Jack:
            return "jack"
        case .Queen:
            return "queen"
        case .King:
            return "king"
        default:
            return String(self.rawValue)
        }
    }
}
swift 再识枚举变量

// 上面的例子中可以看到,枚舉創建時指定的類型是Int型,可以指定rawValue的初始值,默認從0開始,swift中的枚舉值還可以是浮點值和字符串。

In the example above, the raw-value type of the enumeration is Int, so you only have to specify the first raw value. The rest of the raw values are assigned in order. You can also use strings or floating-point numbers as the raw type of an enumeration. Use the rawValue property to access the raw value of an enumeration member.

swift 再识枚举变量

//原始值与关联值:原始值是在你定义枚举的代码中被设置为预填充值的,对于一个特定的枚举成员的原始值始终是相同的。关联值是当你创建一个基于枚举的成员的新的常量或变量的时候设置的,并且每次都可以是不同的。

An instance of an enumeration member can have values associated with the instance. Instances of the same enumeration member can have different values associated with them. You provide the associated values when you create the instance. Associated values and raw values are different: The raw value of an enumeration member is the same for all of its instances, and you provide the raw value when you define the enumeration.

// 示例代码,对一个enum在定义时指定raw type后,可以指定raw Value

enum valueKind:String{
    case name = "xiao ming"
    case age = "19"
}

var value = valueKind.name
value = valueKind.age

// 示例代码,对于枚举成员类型不一致的可以这样定义,在实例化为某一成员时再指定关联值,这样对于同一枚举成员示例出的值可以是不一样的。

enum ServerResponse {
    case Result(String, String)
    case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")

可以看到,swift 的语言灵活度很大,使用Rank(rawValue: <#Int#>) 获取的是一个optional ,需要先解包才能使用。enum的使用比較簡單,同過例子和官方的文檔很容易掌握。本人學習ios時間比較短,博客中寫的不對的地方還請大家多多執政。