我正在寻找一种在 Swift 中打印关联枚举值的方法。IE。以下代码应该"ABCDEFG"为我打印,但它没有。
enum Barcode {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
var productCode = Barcode.QRCode("ABCDEFG")
println(productCode)
// prints (Enum Value)
Run Code Online (Sandbox Code Playgroud)
阅读这个stackoverflow 问题的答案,它与打印枚举的原始值有关,我尝试了以下代码,但它给了我一个错误
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)
// ^
Run Code Online (Sandbox Code Playgroud)
由于我是 Swift 的新手,我无法理解错误消息是关于什么的。有人可以知道这是否可能。
问题是您向Barcodeenum\xe2\x80\x94添加了显式原始类型String。声明其符合Printable您只需要
enum Barcode: Printable {\n case UPCA(Int, Int, Int, Int)\n case QRCode(String)\n var description: String {\n // ...\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n编译器的抱怨是您没有使用非整数原始值类型指定原始值,但无论如何您都不能使用关联值来指定原始值。没有关联类型的原始字符串值可能如下所示:
\n\nenum CheckerColor: String, Printable {\n case Red = "Red"\n case Black = "Black"\n var description: String {\n return rawValue\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1561 次 |
| 最近记录: |