作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在寻找一种方法来在 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 的答案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)
// ^
由于我是 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 - 如何在 Swift 枚举中打印关联值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29506092/
我是一名优秀的程序员,十分优秀!