在这段代码中,我编写了一个非常无用的枚举,它用 Int 或 Float 定义了一个可能的 Number
。
我不明白如何访问我通过关联设置的值。如果我尝试打印它,我只会得到 (Enum Value)
enum Number {
case int (Int)
case float (Float)
}
let integer = Number.int(10)
let float = Number.float(10.5)
println("integer is \(integer)")
println("float is \(float)")
最佳答案
为了完整起见,枚举的关联值也可以使用带有模式匹配的 if 语句来访问。这是原始代码的解决方案:
enum Number {
case int (Int)
case float (Float)
}
let integer = Number.int(10)
let float = Number.float(10.5)
if case let .int(i) = integer {
print("integer is \(i)")
}
if case let .float(f) = float {
print("float is \(f)")
}
此解决方案在以下内容中有详细描述:https://appventure.me/2015/10/17/advanced-practical-enum-examples/
关于swift - 在 Swift 中访问枚举关联值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24263539/