Jean-Philippe Pellet Jean-Philippe Pellet - 3 months ago 7
Swift Question

Is there a way to bind a variable to multiple alternatives in a switch statement?

Suppose I have an enum definition as follows:

enum Response {
case Result(String, Int)
case Error(String)
}


Then, I get such a response:

let resp: Response = // ...


Suppose I want to write a switch statement and handle the same way the Result and the Error cases and bind a variable of the same name to the
String
they contain. How can I do this? Conceptually, something similar to this:

switch resp {
case let .Result(str, _), let .Error(str):
println("Found: \(str)")
}


where
str
is bound twice, and
_
signals that I'm not interested in the
Int
value that a
Result
carries.

So far, the closest thing I could find was to declare an inline function like this and then call it:

func processRespString(str: String) {
println("Found \(str)")
}

switch resp {
case let .Result(str, _): processRespString(str)
case let .Error(str): processRespString(str)
}


Is there a better way?

Answer

No, but if you want to access the String value of a Response regardless of whether it is a .Result or an .Error, you can do this:

enum Response {
    case Result(String, Int)
    case Error(String)

    func Message() -> String {
        switch self {
            case let .Result(str, _):
                return str
            case let .Error(str):
                return str
        }
    }
}

var resp: Response = .Error("Fault")
resp = .Result("Success",5)

println(resp.Message())

This way you keep the logic for the enum inside the enum itself.