# Swift教程(八)--枚举

### 枚举定义语法

```enum CompassPoint {
case north
case south
case east
case west
}```

```enum CompassPoint {
case north,south, east, west
}```

`var myNorth  = CompassPoint.north`

`var mySouth:CompassPoint = .south`

### 枚举的使用

```switch myNorth {
case .north:
print("north")
case .south:
print("south")
case .east:
print("east")
case .west:
print("west")
}```

```switch myNorth {
case .north:
print("north")
case .south:
print("south")
case .east:
print("east")
default:
print("west")
}```

### 关联值(Associated Values)

```enum Shape {
case Rectangle(CGRect)
case Circle(CGPoint,Int)

}```

```var rect = Shape.Rectangle(CGRect(x: 1, y: 1, width: 100, height: 100))

var circle = Shape.Circle(CGPoint(x: 1, y: 1), 2)```

```switch rect {
case .Rectangle(let rect):
print(rect)
}
//输出：(1.0, 1.0, 100.0, 100.0)```

### 原始值(Raw Values)

```enum WeekDayWithRaw : String {
case Monday = "1. Monday"
case Tuesday = "2. Tuesday"
case Wednesday = "3. Wednesday"
case Thursday = "4. Thursday"
case Friday = "5. Friday"
case Saturday = "6. Saturday"
case Sunday = "7. Sunday"

}```

```print(WeekDayWithRaw.Saturday.rawValue)
//输出：6. Saturday```

`let day = WeekDayWithRaw(rawValue: "3. Wednesday")`

```if let day = WeekDayWithRaw(rawValue: "3. Wednesday") {
print(day)
}else{
print("error")
}

//输出：Wednesday```

48 篇文章30 人订阅

0 条评论

## 相关文章

10420

14610

11220

67420

13930

11640

21020

### Xcode10.2 继承UITableView协议失效

前言：在这次App版本迭代进入集成测试阶段尾声，正式环境打包release环境后，测试回归发现许多包含 tableView 的页面都无法响应点击事件。但是在 ...

15060

1.4K30

### React：Table 那些事（2）—— 解读 W3C 规范

—— https://www.w3.org/TR/CSS22/sample.html

20530