Switch statement

Syntax

A switch statement starts with the switch keyword.

switch 5 {
    case 5 {
        puts 'OK'
    }
    case 10 {
        puts 'Nope'
    }
}

The value after can be any expression, but the value after case must be constants.

When this code executes, it looks up the matched case and executes code in this case.

There is no thing like break in C-family languages. So the case body will get out of switch after executed.

It works fine with string or any value.

var b = 'Hi'

switch b {
    case 'Hello' {
        puts 'Not OK'
    }
    case true, false, 10, 'a' {
        puts 'Noop'
    }
    default {
        puts 'It is ' + b
    }
}

Default case

Put a default to make default case:

You will get error if the switch has multiple default.

Multi-condition

You can put multiple conditions after case.

Like default, duplicate condition is not allowed.

Last updated

Was this helpful?