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