首页 > 代码库 > Swift-8-枚举

Swift-8-枚举

// Playground - noun: a place where people can playimport UIKit// 枚举语法enum SomeEnumeration {    // enumeration definition goes here}// 定义一个枚举enum CompassPoint {    case North    case South    case East    case West}// 声明枚举时,并不会像C/OC那样为枚举成员赋默认值// 多个枚举成员出现在一行用逗号隔开enum Planet {    case Mercury, Venus, Earth, Mars}var directionHead = CompassPoint.West// 变量directionHead现在已知为CompassPoint类型,再次赋值时可以省略枚举类型directionHead = .South// 通过Switch匹配枚举值switch directionHead {    case .North:        println("north")case .South:    println("south")case .West:    println("west")case .East:    println("east")default:    break}// 关联值 Associated Valuesenum BarCode {    case UPCA(Int, Int, Int, Int) // UPCA 类型为(Int, Int, Int, Int)    case QRCode(String) // QRCode 类型为 (String)}var productCode = BarCode.UPCA(8, 890, 89, 99)productCode = .QRCode("ABCDEFG")// 提取关联值 使用let还是var根据case语句内的使用情况决定switch productCode {    case .UPCA(let a1, let a2, let a3, let a4):        println("UPCA:\(a1)-\(a2)-\(a3)-\(a4)")    case .QRCode(let s1):        println("QRCode:\(s1)")    default:        break}// 原始值 Raw Valuesenum ASCIIControlCharacter: Character {    case Tab = "\t"    case LineFeed = "\n"    case CarriageReturn = "\r"}// 注意:原始值和关联值是不同的。对于一个特性的枚举成员,它的原始值始终是定义枚举时预设的值,而关联值当你通过一个枚举成员创建变量或者常量时会被设置,每一次都可以不一样// 当整数[ntegers]被用于初始化原始值时,如果其它成员没有特别指定初始值,原始值将会自增enum SomePlanet: Int {    case Mercury = 1, Venus, Earth, Mars, Jupiter, Santurn, Uranus, Neptune}// 通过rawValue属性访问枚举成员let earthsOrder = SomePlanet.Earth.rawValue// 通过原始值初始化实例let possiblePlanet = SomePlanet(rawValue: 7) // 返回值为optional?

 

Swift-8-枚举