Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify switch expression usage #4887

Merged
merged 5 commits into from
May 16, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 23 additions & 11 deletions src/language/branches.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,20 +129,23 @@ check out the patterns documentation on [Switch statements and expressions][].

### Switch expressions

A `switch` expression is similar to a `switch` statement, but you can use them
anywhere you can use an expression. They produce a value based on the expression
body of whichever case matches.
A `switch` _expression_ produces a value based on the expression
body of whichever case matches.
You can use a switch expression wherever Dart allows expressions,
_except_ at the start of an expression statement. For example:

The syntax of a `switch` expression differs from `switch` statement syntax:
```dart
var x = switch (y) { ... };

- Cases _do not_ start with the `case` keyword.
- A case body is a single expression instead of a series of statements.
- Each case must have a body; there is no implicit fallthrough for empty cases.
- Case patterns are separated from their bodies using `=>` instead of `:`.
- Cases are separated by `,` (and an optional trailing `,` is allowed).
- Default cases can _only_ use `_`, instead of allowing both `default` and `_`.
print(switch (x) { ... });

return switch (x) { ... };
```

Switch expressions allow you to rewrite a _statement_ like this:
If you want to use a switch at the start of an expression statement,
use a [switch statement](#switch-statements).

Switch expressions allow you to rewrite a switch _statement_ like this:

```dart
// Where slash, star, comma, semicolon, etc., are constant variables...
Expand Down Expand Up @@ -170,6 +173,15 @@ token = switch (charCode) {
};
```

The syntax of a `switch` expression differs from `switch` statement syntax:

- Cases _do not_ start with the `case` keyword.
- A case body is a single expression instead of a series of statements.
- Each case must have a body; there is no implicit fallthrough for empty cases.
- Case patterns are separated from their bodies using `=>` instead of `:`.
- Cases are separated by `,` (and an optional trailing `,` is allowed).
- Default cases can _only_ use `_`, instead of allowing both `default` and `_`.

{{site.alert.version-note}}
Switch expressions require a [language version][] of at least 3.0.
{{site.alert.end}}
Expand Down