over 6 years ago

Enumerations 定義了一組值,每個值在型別上都屬於這個 enumeration,而每個值可以有任何型別的初始值。

宣告語法

enum myEnum {
    case a
    case b
    case c
}
var e = myEnum.a

因為 e 的型別宣告為 myEnum,所以可以直接指定 myEnum 的 value。

e = .b

Enumerations 值的型別

對 enum 內部的值定義相關的型別,且只能儲存單一的值,也就是如果先給予 a 值,再給予 b,只會保留 b。
取出的方法是使用 switch 取出。

enum myEnum {
    case a(Int, Int)
    case b(String)
}
var e = myEnum.a(1,2)
e = .b("12")

swith e {
case .a(let v1, let v2):
    print("a")
case .b(let value):
    print("b")
}

Enumerations 值的初始值

設定 enum 的初始值,代表內部值的初始值都是相同型別。

enum myEnum: String {
    case a = "a"
    case b = "b"
}

如果使用 Int,定義第一個 case,後續會按照順序自動加上。

enum myEnum: Int {
    case a = 1, b, c ,d
}

如果使用 String 型別,會自動以 enum 的值名稱當做值。

enum myEnum: String {
    case a
    case b
}

取得初始值的方法。

enum myEnum: String {
    case a
    case b
}
let e = myEnum.a.rawValue

透過 rawValue 宣告 enum 型別

如果初始值沒有在 enum 內的值定義,會回傳 nil,一般會回傳 optionals。

enum myEnum: String {
    case a
    case b
}
let e = myEnum(rawValue: "123")

遞迴 enum

若要把 enum 當作 enum 值的型別,需要在 enum 前面加上 indirect。

indirect enum myEnum {
    case a
    case b
    case c(a,b)
}
← iOS Swift : Closures iOS Swift : Classes and Structures →