//声明枚举类型
enum Direction {
#if false
case north
case south
case east
case west
#else
case north,south,east,west
#endif
}
//初始化未指明类型时需要:类型.枚举值
var dir = Direction.east
//当变量类型已知时无需写类型:.枚举值
dir = .east //东
var dir2: Direction = .south
switch dir {
case .north:
print("北")
case .south:
print("南")
case .east:
print("东")
case .west:
print("西")
}
//原始值
enum Week: Int {
case monday = 100,tuesday,wednesday,thursday,friday,saturday,sunday
}
print(Week.friday.rawValue)//104
//将一个原始值转换枚举变量,会得到一个可选类型的变量(因为可能会失败)
let dayOne = Week(rawValue: 102)
if let day = dayOne {
print(day)//wednesday
}
//枚举关联值
enum Point {
case start(x: Double,y: Double)
case end(x: Double,y: Double)
case center(x: Double,y: Double)
}
var point = Point.start(x: 0,y: 0)
point = .end(x: 10,y: 10)
point = .center(x: 5,y: 5)
switch point {
case .start(let x,let y):
print("起点(\(x),\(y))")
case .end(let x,19)"> print("终点(\(x),\(y))")
case .center(let x,19)"> print("中点(\(x),\(y))")
}
原文链接:https://www.f2er.com/swift/321702.html