๐ŸŽ“ A1Learner
๐Ÿ”
0 of 24 lessons completed

Dart Pattern Guards

A pattern guard is a when clause that adds a boolean test to a case. The case matches only when its pattern matches and the guard also gives true.

A guarded variable pattern

The first arm binds the value to n and adds a guard on it. The value 4 passes the guard, and the value 7 falls through to the unguarded arm.

void main() {
  var numbers = [4, 7];
  for (var value in numbers) {
    var word = switch (value) {
      int n when n.isEven => 'even $n',
      int n => 'odd $n',
      _ => 'other',
    };
    print(word);
  }
}

Guarded cases in a switch statement

The statement form puts the guard after the case pattern. The score 150 passes the guard, and the score 40 moves past it to the plain case.

void main() {
  var scores = [150, 40];
  for (var score in scores) {
    switch (score) {
      case int n when n > 100:
        print('big $n');
      case int n:
        print('small $n');
    }
  }
}

A guard with two tests

The first guard needs both tests to pass. The value -4 fails the second test, so it lands on the simpler even arm.

void main() {
  var values = [6, -4, 3];
  for (var value in values) {
    var label = switch (value) {
      int n when n.isEven && n > 0 => 'positive even',
      int n when n.isEven => 'even',
      _ => 'odd',
    };
    print('$value is $label');
  }
}

Example

void main() {
  var scores = [95, 82, 67, 45];
  for (var score in scores) {
    var band = switch (score) {
      int n when n >= 90 => 'top',
      int n when n >= 70 => 'middle',
      int n when n >= 50 => 'low',
      _ => 'below',
    };
    print('$score: $band');
  }
}

Key points

  • A guard is written with the word when after the pattern of a case.
  • The pattern must match first, and the guard test must then give true.
  • The guard can read the variable that the pattern bound.
  • A failed guard does not end matching, and the switch moves on to the next case.
  • Guards work in switch expressions and in switch statements.
  • A guard can combine two tests with &&, so one pattern can split into finer cases.

In this example, every score matches the same int pattern, so the pattern alone cannot split the scores into bands. Each guard tests the bound value n against a lower edge. The first guard that gives true chooses the band, and a score under 50 reaches the wildcard arm.

Note

The pattern decides the shape, and the guard decides whether that shape is accepted.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

A case has the pattern int n and the guard when n > 10. What happens when the value is 5?