Swift学习笔记(10)--枚举

1.定义语法:

enum SomeEnumeration {
// enumeration definition goes here
}

2.使用

enum CompassPoint {
case North
case South
case East
case West
} var directionToHead = CompassPoint.West directionToHead = .South
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")
default:
println("Nothing")
}

  注:1.变量一个次赋值为枚举类型以后,第二次赋值可以使用点语法省略,即.South

    2.switch中必须覆盖所有的枚举类型,如果太多,可使用default

3.相关值(Associated Values)

swift语句中可以储存任何类型的相关值

enum Chazidian {
case Pianpang(String, String)
case Zimu(String)
case Bihua(Int)
} var c1 = Chazidian.Pianpang("一","田")
var c2 = Chazidian.Zimu("a")
var c3 = Chazidian.Bihua(3) switch c3 {
case .Pianpang(let s1, let s2):
println("偏旁:\(s1),\(s2)")
case .Zimu(let s3):
println("字母:\(s3)")
case .Bihua(let s4):
println("笔画:\(s4)")
} //笔画:3

  

3.默认值

swift中枚举的默认值需要自己手动添加:

//方式1:对每一个做赋值
enum ASCIIControlCharacter: Character {
case Tab = "\t"
case LineFeed = "\n"
case CarriageReturn = "\r"
} //方式2:自动递增
enum Planet: Int {
case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}

  

上一篇:Python爬虫与一汽项目【二】爬取中国东方电气集中采购平台


下一篇:JDK源码学习笔记——Enum枚举使用及原理