所谓的关联值,就是可以在枚举中可以存储数据
所谓的原始值,就是默认的数据
关联值(Associated Values)
我们可以定义Swift枚举来存储任何给定类型的关联值,而且每种枚举情况的值类型可以不同。
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
//创建Barcode枚举实例
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
可以将关联值提取为switch语句的一部分。将每个关联值提取为常量(let)或变量(var),以便在switch中处理:
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
print("QR code: \(productCode).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."
如果枚举case的所有关联值都被提取为常量,或者都被提取为变量,则可以将var或let放置在case名称前面,来提取所有的关联值:
switch productBarcode {
case let .upc(numberSystem, manufacturer, product, check):
print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).")
case let .qrCode(productCode):
print("QR code: \(productCode).")
}
// Prints "QR code: ABCDEFGHIJKLMNOP."
5.原始值(Raw Values)
关联值
表明了枚举如何存储不同类型的关联值。作为关联值的替代,枚举情况可以预先设置默认值(称原始值
),它们都是相同的类型。
原始值可以是字符串,字符,整数或浮点数类型。每个原始值在其枚举声明中必须是唯一的。
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
注意
:原始值是不一样的关联值。当您首次在代码中定义枚举时,原始值将设置为预填充值,如上面的三个ASCII代码。特定枚举情况的原始值始终相同。根据枚举的情况创建新常量或变量时,将设置关联值,每次执行此操作时可能会有所不同。
网友评论