【Swift4】(7) 枚举 | 应用

2023-10-07 18:24:54 浏览数 (3)

枚举基本使用

表述一组值

枚举相当于创建了一种新的数据类型,而类型的取值由里面的case值进行表征

代码语言:javascript复制
enum CompassPoint { // 大写开头
    case north,west,east,south
}
代码语言:javascript复制
enum GameEnding {
    case Win
    case Lose
    case Draw
}

var yourScore:Int  = 100
var enemyScore:Int = 100

var thisGameEnding:GameEnding
if yourScore > enemyScore {thisGameEnding = GameEnding.Win}
else if yourScore == enemyScore {thisGameEnding = GameEnding.Draw}
else {thisGameEnding = .Lose}  //可省略GameEnding
switch thisGameEnding
{
case .Win: print("win") 
case .Draw: print("Draw")
case .Lose: print("Lose")
}
代码语言:javascript复制
enum VowleCharacter:Character {
    case A = "a"
    case E = "e"
    case I = "i"
    case O = "o"
    case U = "u"
}

let vowelA = VowleCharacter.A

var userInputCharacter:Character = "a"
if userInputCharacter == vowelA.rawValue
{
    print("it is an 'a'")   //"it is an 'a'n"
}else {
    print("it is not an 'a'")
}
灵活使用
代码语言:javascript复制
enum Barcode {
    case UPCA(Int,Int,Int,Int)
    case QRCode(String)   //将枚举变量QRCode关联为String类型
}

let productCodeA = Barcode.UPCA(4, 102, 306, 8)
let productCodeB = Barcode.QRCode("This is a infomation")

switch productCodeA {
case .UPCA(let numberSystem,let manufacture,let identifier,let check):
    print("UPC-A with value of (numberSystem), (manufacture), (identifier),(check).")   //"UPC-A with value of 4, 102, 306,8.n"
case .QRCode(let productCode):
    print("QRCode with value of (productCode).")
}

0 人点赞