Fork me on GitHub

以撸代码的形式学习Swift-8:枚举(Enumerations)

一等(first-class)类型
每个枚举定义了一个全新的类型。以大写字母开头
成员值(或成员) 原始值 关联值
不会被赋予一个默认的整型值

1 枚举语法

1
2
3
4
5
6
7
8
9
10
11
enum CompassPoint {
case North
case South
case East
case West
}
enum Planet {
case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
}
var directionToHead = CompassPoint.West
directionToHead = .East

2 Switch 语句匹配枚举值

1
2
3
4
5
6
7
8
9
10
switch directionToHead {
case .North:
print("Lots of planets have a north")
case .South:
print("Watch out for penguins")
case .East:
print("Where the sun rises")
case .West:
print("Where the skies are blue")
}

3 关联值(Associated Values) 任意类型,可以各不相同

“定义一个名为 Barcode 的枚举类型,它的一个成员值是具有 (Int,Int,Int,Int) 类型关联值的 UPCA ,另一个成员值是具有 String 类型关联值的 QRCode 。”

1
2
3
4
5
6
7
8
9
10
11
12
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):
print("UPC-A: \(numberSystem), \(manufacturer), \(product), \(check).")
case .QRCode(let productCode):
print("QR code: \(productCode).")
}

4 原始值(Raw Values)

5 递归枚举(Recursive Enumerations)

playground文件在andyRon/LearnSwift


--------------------本文结束👨‍💻感谢您的阅读--------------------
坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文标题: 以撸代码的形式学习Swift-8:枚举(Enumerations)
  • 本文作者: AndyRon
  • 发布时间: 2017年07月03日 - 13:40
  • 最后更新: 2018年12月26日 - 17:24
  • 本文链接: http://andyron.com/2017/swift-8-enumerations.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!
0%