Swift Control Constructs
Swift script provides if, switch, foreach, and iterate constructs, with syntax and semantics similar to comparable constructs in other high-level languages.
foreach
The foreach construct is used to apply a block of statements to each element in an array. For example:check_order (file a[]) {
foreach f in a {
compute(f);
}
}
foreach statements have the general form:
foreach controlvariable (,index) in expression {
statements
}
The block of statements is evaluated once for each element in expression which must be an array, with controlvariable set to the corresponding element and index (if specified) set to the integer position in the array that is being iterated over.
if
The if statement allows one of two blocks of statements to be executed, based on a boolean predicate. if statements generally have the form:
if(predicate) {
statements
} else {
statements
}
where predicate is a boolean expression.
switch
switch expressions allow one of a selection of blocks to be chosen based on the value of a numerical control expression. switch statements take the general form:
switch(controlExpression) {
case n1:
statements2
case n2:
statements2
[...]
default:
statements
}
The control expression is evaluated, the resulting numerical value used to select a corresponding case, and the statements belonging to that case block are evaluated. If no case corresponds, then the statements belonging to the default block are evaluated.
Unlike C or Java switch statements, execution does not fall through to subsequent case blocks, and no break statement is necessary at the end of each block.
Following is an example of a switch expression in Swift:
int score=60;
switch (score){
case 100:
tracef("%s\n", "Bravo!");
case 90:
tracef("%s\n", "very good");
case 80:
tracef("%s\n", "good");
case 70:
tracef("%s\n", "fair");
default:
tracef("%s\n", "unknown grade");
}
iterate
iterate expressions allow a block of code to be evaluated repeatedly, with an iteration variable being incremented after each iteration.
The general form is:
iterate var {
statements;
} until (terminationExpression);
Here var is the iteration variable. Its initial value is 0. After each iteration, but before terminationExpression is evaluated, the iteration variable is incremented. This means that if the termination expression is a function of only the iteration variable, the body will never be executed while the termination expression is true.
Example:
iterate i {
trace(i); // will print 0, 1, and 2
} until (i == 3);
Variables declared inside the body of iterate can be used in the termination expression. However, their values will reflect the values calculated as part of the last invocation of the body, and may not reflect the incremented value of the iteration variable:
iterate i {
trace(i);
int j = i; // will print 0, 1, 2, and 3
} until (j == 3);