如何从枚举案例的特定实例中提取关联值?



考虑这个枚举...

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

如果它传递到函数中,则可以使用每个情况接收关联值的开关语句,例如...

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

那么,与此可能相似吗?

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

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

最新更新