在 Apple 的“A swift Tour”中,他们有这样的代码片段:
enum OptionalValue<T> {
case None
case Some(T)
}
var possibleInteger: OptionalValue<Int> = .None
possibleInteger = .Some(100)
您将如何获得 100?你不能做 possibleInteger == 100
测试是否possibleInteger
里面的值为 100。我知道您可以将函数放在枚举中,但不能有变量。也许我对枚举的理解有误……
如果我命令点击 Optional
当声明一个可选的(var x:Optional<Int>
)时,我可以找到
enum Optional<T> : Reflectable, NilLiteralConvertible {
case None
case Some(T)
init()
init(_ some: T)
/// Haskell's fmap, which was mis-named
func map<U>(f: (T) -> U) -> U?
func getMirror() -> MirrorType
static func convertFromNilLiteral() -> T?
}
但是我不明白那是什么意思。帮忙?
最佳答案
您可以使用 switch
语句来获取值 as described here .相关位:
... the associated values can be extracted as part of the switch statement. You extract each associated value as a constant (with the let prefix) or a variable (with the var prefix) for use within the switch case’s body:
对于你的情况,你会想要这样的东西:
switch possibleInteger {
case .Some(let value):
println(value)
case .None:
println("<None>")
}
关于enums - 如何获取枚举值的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25570757/