foreach, break

Syntax

foreach (variableName in collection) {
    body
}
or
foreach (variableName : typeName in collection) {
    body
}

where:

Description

The foreach statement processes some statements for each element contained within a collection. It processes the code between the braces for the 1st element, then for the 2nd element, then for the 3rd element, etc until it passes the last one.

You may leave the foreach loop before it passes the last element of the collection using the break directive.

Examples

This code processes a UML package contents and calls a rule with each owned element name as argument :

myPackage : uml21.Package = ...;
foreach (element in myPackage.ownedElement)
    @myRule(element.name);
}

We could decide to break the loop when we encouter the name 'Customer' :

myPackage : uml21.Package = ...;
foreach (element in myPackage.ownedElement)
    @myRule(element.name);
    
    // break if we encounter a 'Customer' name
    if (element.name == "Customer") {
        break;
    }
}