@phper 2015-03-31T15:43:01.000000Z 字数 2384 阅读 2307

# swift 10 枚举

swift

## 枚举语法

enum SomeEnumeration {
case **
//enumeration definition goes here
}


enum compasspoint {
case North
case South
case East
case West
}


enum compasspoint {
case North,South,East,West
}


var directionToHead = CompassPoint.West


directionToHead的类型被推断当它被CompassPoint的一个可能值初始化。一旦directionToHead被声明为一个CompassPoint，你可以使用更短的点.语法将其设置为另一个CompassPoint的值：

directionToHead = .East


PS: 妈的，说实话，上面这几段真没看懂，完全不知道在讲些啥！

## 匹配枚举值和Switch语句

enum compasspoint {    case North,South,East,West}var directionToHead = compsspoint.East//省略里，用.代替，可以自动识别。directionToHead = .Southswitch directionToHead {case .North: #可以省略    println("Lots of planets have a north")case .South:    println("Watch out for penguins")case .East:    println("Where the sun rises")case .West:    println("Where the skies are blue")default:    println("Not a safe place for humans")}// 输出 "Watch out for penguins”

“考虑directionToHead的值。当它等于.North，打印“Lots of planets have a north”。当它等于.South，打印“Watch out for penguins”。”

## 原始值

enum ASCIIControlCharacter: Character {    case Tab = "\t"    case LineFeed = "\n"    case CarriageReturn = "\r"}

enum Planet: Int {    case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune}

rawValue方法可以或者一个枚举成员的原始值

let earthsOrder = Planet.Earth.rawValue
// earthsOrder is 3


let possiblePlanet = Planet(rawValue: 7)
// possiblePlanet is of type Planet? and equals Planet.Uranus


let positionToFind = 9if let somePlanet = Planet(rawValue: positionToFind) {    switch somePlanet {    case .Earth:        println("Mostly harmless")    default:        println("Not a safe place for humans")    }} else {    println("There isn't a planet at position \(positionToFind)")}// 输出 "There isn't a planet at position 9

• 私有
• 公开
• 删除