I need to iterate a for
loop nested inside of a while
loop for several different conditions.
The only change in the code for each statement is the comparison condition to apply.
Turns out I am copy-pasting all of the code multiple times and changing the direction of the greater-less than symbol.
for example:
if (direction.horizontal == UIScrollDirectionLeft) {
int column = startColumn+1;
while (column < maxAllowed) {
for (int row = minRow; row < maxRow; row++) {
repeated code
}
column++;
} else {
int column = minColumn -1;
while (column >= 0) {
for (int row = minRow; row < maxRow; row++) {
repeated code
}
column--;
}
}
Is it possible to do a macro for the condition operator in order to facilitate code reuse?
I would really like something which could look like this:
int startColumn = (direction.horizontal == UIScrollDirectionLeft) ? (startColumn+1) : minColumn -1;
SignOfOperator theSignInTheWhile = (direction.horizontal == UIScrollDirectionLeft) ? "<" : ">=";
int conditionToTestInWhile = (direction.horizontal == UIScrollDirectionLeft) ? maxAllowed : 0;
while(startColumn,theSignInTheWhile,conditionToTestInWhile) {
// repeated code
}
I have another 4 cases like the one above...
You only need the loop code once. Just change the step value and terminating value. For example:
int start_column, end_column, column_step;
:
switch (direction.horizontal) {
case UIScrollDirectionLeft:
column = start_column + 1;
column_step = 1;
end_column = max_allowed;
break;
case UIScrollDirectionRight:
column = min_column - 1;
column_step = -1;
end_column = -1;
break;
:
}
while (column != end_column) {
for (int row = minRow; row < maxRow; row++) {
repeated_code();
}
column += column_step;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.