Getting value from do/catch Syntax

I love the ability to use switch statements to declare a variable. A simple example below.

    let i : Int = .random()

    

    let someVar : String = switch i.odd { //odd is an extension I have to determine if a number is odd or even. It returns a bool.

    case false: "even"

    case true: "odd"

    }

Is it possible to do something similar with a do / catch statement? The control flow seems odd in my below example, but the idea is that if an initial variable couldn’t be created, then some other way could be done, and you can just keep on going until complete failure.


    let someVar = do {

      try someFunctionThatReturnsVar()

    } catch SomeError.varDoesNotExist { //if initial doesn't work, then depending on error, go to correct catch statement

      try createVar()

    } catch { //catching all other errors would either throw or return nil

      print("fail: kill flow here")

      throw SomeError.failedToCreateVar

    }

https://forums.swift.org/t/pitch-multi-statement-if-switch-do-expressions/

There's a bunch about it in here too:
https://forums.swift.org/t/pitch-last-expression-as-return-value/

Thank you! That really tackles the issue.

1 Like