枚举

目录

常规用法

1
2
3
4
5
6
enum accountType {
    case email
    case phone
}
accountType.email
accountType.phone

关联值

有时将枚举的成员值跟其他类型的值关联存储在一起,会非常有用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
enum Password {
    case number(Int, Int, Int, Int) // 32
    case other

}
var pwd = Password.number(5, 6, 4, 7) // 33
pwd = .other // 0

var pwd2 = Password.number(10, 9, 100, 19999)
var pwd3 = Password.number(111, 222, 100, 19999)



enum Date {

    case digit(year:Int,month:Int,day:Int)

    case string(String)

}

var date = Date.digit(year: 2024, month: 4, day: 9)

date = .string("2024-04-09")

  

switch date {

case .digit(let year,let month, let day):

    print(year,month,day)

case let .string(value):

    print(value)

}

原始值

枚举成员可以使用相同类型的默认值预先对应,这个默认值叫做:原始值 如果枚举的原始值类型是Int、 String, Swift会自动分配原始值

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
 enum poker:Character{
    case spade = "♠"
    case heart = "♥"
    case diamond = "♦️"
    case club = "♣"
}

var suit = poker.spade
print(suit)
print(suit.rawValue)
print(poker.spade.rawValue)