如何打印 Swift 枚举中的关联值?
How to print associated values in Swift enumerations?
我正在寻找一种方法来打印 Swift 中枚举的关联值。 IE。下面的代码应该为我打印 "ABCDEFG"
但它没有。
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
var productCode = Barcode.QRCode("ABCDEFG")
println(productCode)
// prints (Enum Value)
阅读 this Whosebug 问题的答案,该问题与打印枚举的原始值有关,我尝试了以下代码,但它给了我一个错误
enum Barcode: String, Printable {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
var description: String {
switch self {
case let UPCA(int1, int2, int3, int4):
return "(\(int1), \(int2), \(int3), \(int4))"
case let QRCode(string):
return string
}
}
}
var productCode = Barcode.QRCode("ABCDEFG")
println(productCode)
// prints error: enum cases require explicit raw values when the raw type is not integer literal convertible
// case UPCA(Int, Int, Int, Int)
// ^
由于我是 Swift 的新手,所以我无法理解错误消息的内容。有人知道可不可以吗
问题是您向 Barcode
枚举添加了显式原始类型 — String
。声明它符合 Printable
是你所需要的:
enum Barcode: Printable {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
var description: String {
// ...
}
}
编译器的抱怨是你没有用你的非整数原始值类型指定原始值,但你不能用关联值这样做。没有关联类型的原始字符串值可能如下所示:
enum CheckerColor: String, Printable {
case Red = "Red"
case Black = "Black"
var description: String {
return rawValue
}
}
我正在寻找一种方法来打印 Swift 中枚举的关联值。 IE。下面的代码应该为我打印 "ABCDEFG"
但它没有。
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
var productCode = Barcode.QRCode("ABCDEFG")
println(productCode)
// prints (Enum Value)
阅读 this Whosebug 问题的答案,该问题与打印枚举的原始值有关,我尝试了以下代码,但它给了我一个错误
enum Barcode: String, Printable {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
var description: String {
switch self {
case let UPCA(int1, int2, int3, int4):
return "(\(int1), \(int2), \(int3), \(int4))"
case let QRCode(string):
return string
}
}
}
var productCode = Barcode.QRCode("ABCDEFG")
println(productCode)
// prints error: enum cases require explicit raw values when the raw type is not integer literal convertible
// case UPCA(Int, Int, Int, Int)
// ^
由于我是 Swift 的新手,所以我无法理解错误消息的内容。有人知道可不可以吗
问题是您向 Barcode
枚举添加了显式原始类型 — String
。声明它符合 Printable
是你所需要的:
enum Barcode: Printable {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
var description: String {
// ...
}
}
编译器的抱怨是你没有用你的非整数原始值类型指定原始值,但你不能用关联值这样做。没有关联类型的原始字符串值可能如下所示:
enum CheckerColor: String, Printable {
case Red = "Red"
case Black = "Black"
var description: String {
return rawValue
}
}