从 Playgrounds 论 Swift(八): 枚举(Enumerations)
从 Playgrounds 论 Swift(8): 枚举(Enumerations)
转载请声明出处:http://blog.****.net/jinnchang/article/details/43268905
原始值可以是字符串,字符,或者任何整型值或浮点型值。
欲了解更细致的请参考官方文档:Enumerations
转载请声明出处:http://blog.****.net/jinnchang/article/details/43268905
1、枚举语法
- 每个成员值通过关键字 case 来定义。
- 成员名字必须以一个大写字母开头。
- 多个成员值可以出现在同一行上,用逗号隔开。
// 定义枚举 enum CompassPoint { case North case South case East case West } enum Planet { case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune } var directionToHead: CompassPoint = CompassPoint.West directionToHead = .East // 当已经推断出变量或常量的枚举类型后,访问时可以不写枚举名 switch 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") } // prints "Where the sun rises"
2、关联值(Associated Values)
Swift 的枚举可以定义为任何类型的关联值,如果需要的话,每个成员的数据类型可以是各不相同的。// 定义了一个包含条形码和二维码的枚举 enum Barcode { case UPCA(Int, Int, Int, Int) case QRCode(String) } var productBarcode = Barcode.UPCA(8, 85909, 51226, 3) productBarcode = .QRCode("ABCDEFGHIJKLMNOP") switch productBarcode { case .UPCA(let numberSystem, let manufacturer, let product, let check): println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).") case .QRCode(let productCode): println("QR code: \(productCode).") } // prints "QR code: ABCDEFGHIJKLMNOP." // 如果关联值中的数据类型一致,可将声明类型提取到成员值前 switch productBarcode { case let .UPCA(numberSystem, manufacturer, product, check): println("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).") case let .QRCode(productCode): println("QR code: \(productCode).") } // prints "QR code: ABCDEFGHIJKLMNOP."
3、原始值(Raw Values)
枚举成员可以被默认值(称为原始值)预先填充,其中这些原始值具有相同的类型。原始值可以是字符串,字符,或者任何整型值或浮点型值。
每个原始值在它的枚举声明中必须是唯一的。当整型值被用于原始值,如果其它枚举成员没有值时,它们会自动递增。
enum Planet: Int { case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune } let earthsOrder = Planet.Earth.rawValue let possiblePlanet = Planet(rawValue: 7) let positionToFind = 9 if 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)") } // prints "There isn't a planet at position 9"
5、枚举是值类型
6、结语
文章最后更新时间:2015年1月30日09:17:00。欲了解更细致的请参考官方文档:Enumerations