Convert switch to if else in Swift

Viewed 969

I want to convert all the switch statements of SwiftyJSON to if-else conditions, because the switch statements are causing lots of memory leaks.

I've almost converted all the switch-statements, but I gut stuck by this:

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)
}

Can someone help me please?

1 Answers
switch sub.jsonKey {
    case .index(let index): return self[index: index]
    case .key(let key): return self[key: key]
}

will be

if case .index(let index) = sub.jsonKey {
    return self[index: index]
} else if case .key(let key) = sub.jsonKey {
    return self[key: key]
}

Or in abstract:

switch value {
   case .a(let x): doFoo(x)
   case .b(let y): doBar(y)
}

becomes

if case .a(let x) = value {
    doFoo(x)
} else if case .b(let y) = value {
    doBar(y)
}
Related