HaxeDoc2

(やまだぃちぅ) #1

3 case 6 | 7: " 1 ";
4 case _: " 2 ";
5 }
6 trace(match); // 1


If there is a captured variable in an or-pattern, it must appear in both its sub-patterns.

6.4.7 Guards........................................


It is also possible to further restrict patterns with thecase ... if(condition):syntax:

1 var myArray = [7, 6];
2 var s = switch(myArray){
3 case [a, b] if (b > a):
4 b + ">" +a;
5 case [a, b]:
6 b + "<=" +a;
7 case _: "found something else";
8 }
9 trace(s); // 6<=7


The first case has an additional guard conditionif (b > a). It will only be selected if that
condition holds, otherwise matching continues with the next case.

6.4.8 Match on multiple values


Array syntax can be used to match on multiple values:

1 var s = switch [1, false, "foo"]{
2 case [1, false, "bar"]: " 0 ";
3 case [, true, ]: " 1 ";
4 case [, false, ]: " 2 ";
5 }
6 trace(s); // 2


This is quite similar to usual array matching, but there are differences:


  • The number of elements is fixed, so patterns of different array length will not be accepted.

  • It is not possible to capture the switch value in a variable, i.e.case xis not allowed (case
    _still is).


6.4.9 Extractors


Since Haxe 3.1.0

Extractors allow applying transformations to values being matched. This is often useful when
a small operation is required on a matched value before matching can continue:

1 enum Test {
2 TString(s:String);
3 TInt(i:Int);
4 }
5
6 class Main {

Free download pdf