enums - 如何获取枚举值的值?

标签 enums swift option-type

在 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/

相关文章:

mysql - 比较两个 SQL 条目的枚举索引

swift - 在 Xcode 9.0.1 的 UITableviewcell 单元格大小中,它在运行时不会扩展?

ios - 如何在 tableview cell swift 中自定义和实现 slider

c++ - experimental::optional nullopt_t 构造函数

java - Java 8 中 Optional 类型的有效使用

ios - 使作为参数传递给另一个函数的函数可选?

java - 将频率转换为 java.time.Period 类型

c++ - 依靠枚举 C++ 自动

ios - 如何加载带有注释信息的 View Controller

c# - WPF 多个枚举标志到转换器参数?