如果添加了标签,那么,每当创建枚举用例时,都需要将这些标签标示出来。
let trade1 = Trade.buy(stock: "APPL", amount: 500)
let trade2 = Trade.sell(stock: "TSLA", amount: 100)
if case let Trade.buy(stock, amount) = trade1 {
print("buy \(amount) of \(stock)") // print buy 500 of APPL
}
if case let Trade.sell(stock, amount) = trade2 {
print("sell \(amount) of \(stock)") // print sell 100 of TSLA
}
let productBarcode1: Barcode = .UPCA(8, 85909_51226, 3)
let productBarcode2: Barcode = Barcode.QRCode("ABCDEFGHIJKLMNOP")
switch productBarcode1 { // print UPC-A with value of 8, 8590951226, 3.
case .UPCA(let numberSystem, let identifier, let check):
print("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case .QRCode(let productCode):
print("QR code with value of \(productCode).")
}
switch productBarcode2 { // print QR code with value of ABCDEFGHIJKLMNOP.
/// 如果所有的枚举成员的关联值的提取为常数,或者当所有被提取为变量,为了简洁起见,可以放置一个 let 或 var
/// 标注在成员名称前
case let .UPCA(numberSystem, identifier, check):
print("UPC-A with value of \(numberSystem), \(identifier), \(check).")
case let .QRCode(productCode):
print("QR code with value of \(productCode).")
}
let code3: Barcode = .QRCode("123")
let code4: Barcode = .QRCode("456")
if code3 == code4 {
}
/// 系统提示:Binary operator '==' cannot be applied to two 'Enum.Barcode' operands, 在 Swift 中,
/// enum 不提供 == 运算符的操作
/// 正确使用方法 使用 switch 去判断类型
switch (code3, code4) { // print code3 == code4: false
case (.QRCode(let a), .QRCode(let b)) where a == b:
print("code3 == code4: true")
default:
print("code3 == code4: false")
}