Is it possible to have multiple statements in a branch of a switch statement?

How can I have multiple statements in a case arm?

  let base_pose = switch lowerBodyState {
    case let .idle(entered):
        assets.get_anim(name: "idle").pose(time: now - entered)
    case let .moving(entered):  
        let bla = "moving"
        assets.get_anim(name: bla).pose(time: now - entered)        
    }
    return base_pose

When I try to have multiple expressions, it does not compile.

\swifting\Sources\animation.swift:92:60: error: non-expression branch of 'switch' expression may only end with a 'throw'
        assets.get_anim(name: bla).pose(time: now - entered)

If I wrap the expressions in a function it compiles but this is extremely clunky.

1 Like

This is a switch expression, not a statement. Currently, switch expressions do not support cases with multiple statements. As you note, you can refactor the multiple statements into a function. You can also refactor the code to use a switch statement by writing something like:

let base_pose: <<type>>
switch lowerBodyState {
case let .idle(entered):
    base_pose = assets.get_anim(name: "idle").pose(time: now - entered)
case let .moving(entered):  
    let bla = "moving"
    base_pose = assets.get_anim(name: bla).pose(time: now - entered)        
}
4 Likes

Ahh thats a bummer, I guess the statement syntax is better than having to write wrapper function.

You say currently unsupported, does that mean multiple statements per case is in the pipeline?

2 Likes

Yeah there’s a pitch which got a bunch of interest and feedback a few weeks back: Pitch: Multi-statement if/switch/do expressions

3 Likes

It is a pitch with the most replies ever on this forum!

1 Like

According to official documentation, regarding switch statements

The body of each case must contain at least one executable statement.

I believe "at least" means that multiple statements are allowed.

But

Like if statements, switch statements also have an expression form
...
You can use switch expressions on the right-hand side of an assignment

Apparently you are using the expression form of the switch keyword. As you are using a value returned by the switch expression, every case should calculate that value. Multiple statements do not return a single value, this is why you get the error message.

1 Like

You can wrap the multiple statements in a closure that’s invoked...

    let v: Int = switch false {
    case true: 
        8
    case false: 
        {
            print("do stuff")
            return 7 
        }()
    }

Or with unconventional placement of the { and }() it has the format you’d want

    let v: Int = switch false {
    case true: 
        8
    case false: {
        print("do stuff")
        return 7 }()
    }
4 Likes