在 Swift 中将 switch 转换为 if else

Mic*_*mhr 3 switch-statement swift swifty-json

我想将 SwiftyJSON 的所有 switch 语句转换为 if-else 条件,因为 switch 语句会导致大量内存泄漏。

我几乎已经转换了所有的 switch 语句,但我被这个困住了:

fileprivate subscript(sub sub: JSONSubscriptType) -> JSON {
    ...
    switch sub.jsonKey {
        case .index(let index): return self[index: index]
        case .key(let key): return self[key: key]
    }
    ...
}

public enum JSONKey {
    case index(Int)
    case key(String)
}
Run Code Online (Sandbox Code Playgroud)

有人能帮助我吗?

use*_*434 5

switch sub.jsonKey {
    case .index(let index): return self[index: index]
    case .key(let key): return self[key: key]
}
Run Code Online (Sandbox Code Playgroud)

将会

if case .index(let index) = sub.jsonKey {
    return self[index: index]
} else if case .key(let key) = sub.jsonKey {
    return self[key: key]
}
Run Code Online (Sandbox Code Playgroud)

或者抽象地说

switch value {
   case .a(let x): doFoo(x)
   case .b(let y): doBar(y)
}
Run Code Online (Sandbox Code Playgroud)

变成

if case .a(let x) = value {
    doFoo(x)
} else if case .b(let y) = value {
    doBar(y)
}
Run Code Online (Sandbox Code Playgroud)