注:摘自斯坦福swift公开课
在swift中,enum(枚举类型)和struct一样都是值类型,进行值传递。和其他语言不同的是在swift中,enum中的每个case可以有与之关联的数据(associated data)。例如:
enum FastFoodMenuItem {
case hamburger(numberOfPatties: Int) //可以有关联的数据
case fries(size: FryOrderSize)
case drink(String, ounces: Int)
case cookie
}
enum FryOrderSize {
case large
case small
}
给enum赋值的方法如下:
let menuItem = FastFoodMenuItem.hamburger(patties: 2)
var otherItem : FastFoodMenuItem = .ccokie
//在使用类型推导时,只能省略等号两侧中的某一侧。如果两侧都省略,则编译器无法推导出类型,会报错如:
var otherItem = .cookie //会报错
在给enum赋值时,如果该case有关联的数据,则要在赋值时就给出该数据。(唯一的机会,后面无法修改)
判断enum的情况时不能使用"==",要使用switch。使用switch时要列出所有的情况,或使用default表示省略的部分。如:
switch menuItem {
case FastFoodMenuItem.hamburger : print("burger")
case FastFoodMenuItem.fries : print("fries")
case FastFoodMenuItem.drink : print("drink")
case FastFoodMenuItem.cookie : print("cookie")
}
//其中FastFoodMenuItem可以省略,swift可以自行推导,例如:
switch menuItem {
case .hamburger : print("burger")
case .fries : print("fries")
case .drink : print("drink")
case .cookie : print("cookie")
}
可以使用let来获取enum中的数据,例如:
var menuItem = FastFoodMenuItem.drink("Coke", ounces: 32)
switch menuItem {
case .hamburger(let pattyCount) : print(pattyCount)
case .fries(let size) : print(size)
case .drink(let brand, let ounces) : print(brand)
case .cookie : print("cookie")
}
enum中可以有方法(method),可以使用self来判断enum的状态和关联值,例如:
enum FastFoodMenuItem {
...
func isIncludeInSpecialOrder(number : Int) -> Bool {
switch self {
case .hamburger(let pattyCount) : return pattyCount == number
case .fries, .cookie : return true
case .drink(_, let ounces) : return ounce == 16
}
}
}