gpt4 book ai didi

swift - 如何在 Swift 枚举中打印关联值?

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:14 26 4
gpt4 key购买 nike

我正在寻找一种方法来在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com