[Swift-d8] - Playground - Enumerations

鐵人賽 Swift Day8:Enumerations 列舉型別介紹,含 Switch 搭配使用、Associated Values 賦予附加資料,以及 Raw Values 設定預設值。

Playground - Enumerations

通常會使用來定義一組相關的值

也是很方便的東西

列舉語法

1
2
3
enum SomeEnumeration {
  // enumeration definition goes here
}

比方說,車子

1
2
3
4
5
enum Car {
	case toyota
	case benz
	case BMW
}

也可以這樣寫

1
2
3
enum Car {
	case toyota, benz, BMW
}

使用:

1
var car = Car.benz

和 Switch 的搭配

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
enum Car {
    case Toyota, Benz, BMW
}

var car = Car.Benz

switch car {
case .Toyota:
    println("Toyota")
case .Benz:
    println("Benz")
case .BMW:
    println("BMW")
}

Associated Values

以 Barcode 來舉例子

1
2
3
4
5
6
enum Barcode {
    case UPCA(Int, Int, Int)
    case QRCode(String)
}

var productBarcode = Barcode.UPCA(12, 8948, 333)

我們可以借此來定義一些結構

Raw Values

我們可以先給定預設值:

1
2
3
4
5
6
7
enum Barcode: String {
    case UPCA = "upca"
    case QRCode = "qrcode"
}

var productBarcode = Barcode.UPCA
println(productBarcode.toRaw())

可以透過 raw value 來找尋

1
println(Barcode.fromRaw("qrcode"))

這個部分雖然不多,但是很實用

comments powered by Disqus
Powered by Hugo. Theme Stack. All Rights Reserved.