我需要迭代for
循环嵌套在while
循环内的几个不同条件。
每个语句的代码中唯一的变化是要应用的比较条件。
原来我多次复制粘贴所有代码并改变大于符号的方向。
例如:
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--;
}
}
是否可以为条件运算符执行宏以便于代码重用?
我真的很喜欢看起来像这样的东西:
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
}
我还有另外4个案例,就像上面那个......
答案 0 :(得分:2)
您只需要一次循环代码。只需更改步长值和终止值即可。例如:
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;
}