【问题标题】:How can you extract associated values from a specific instance of an enum's case?如何从枚举案例的特定实例中提取关联值?
【发布时间】:2018-02-16 02:20:12
【问题描述】:

考虑这个枚举...

enum SelectionMode {
    case none     (position:TextPosition)
    case normal   (startPosition:TextPosition, endPosition:TextPosition)
    case lines    (startLineIndex:Int, endLineIndex:Int)
}

如果它被传递到一个函数中,你可以使用一个 switch 语句,每个 case 接收相关的值,就像这样......

let selectionMode:SelectionMode = .lines(4, 6)

switch sectionMode {
    case let .none   (position): break;
    case let .normal (startPosition, endPosition): break;
    case let .lines  (startLineIndex, endLineIndex):
        // Do something with the indexes here

}

我想知道的是,如果我知道例如我收到了一个“.lines”版本,我怎样才能在不使用 switch 语句的情况下获得相关的值?

即我可以这样做吗?

let selectionMode:SelectionMode = .lines(4, 6)

let startLineIndex = selectionMode.startLineIndex

那么类似的事情可能吗?

【问题讨论】:

    标签: swift enums associated-object


    【解决方案1】:

    没有任何运行时检查的简单赋值是行不通的,因为 编译器无法知道selectionMode 变量包含哪个值。 如果你的程序逻辑保证它是.lines 那么 您可以通过模式匹配提取关联值:

    guard case .lines(let startLineIndex, _) = selectionMode else {
        fatalError("Expected a .lines value")
        // Or whatever is appropriate ...
    }
    

    【讨论】:

    • 完美!正是我想要的。谢谢!
    • 太棒了!这甚至适用于 if 语句。 if case .lines(let startLineIndex, _) = selectionMode { // do stuff }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 2021-11-11
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多