var callbacks = ['a', 'b', 'c', 'd', 'e'];
for( var x in callbacks){
print("for-in - $x");
}
while and do-while loops
조건을 평가하고 루프를 진행 - while
while (!isDone()) {
doSomething();
}
루프를 실행한 후 평가 - do-while
do {
printLine();
} while (!atEndOfPage());
break and continue
while 문으로 반복 실행 중 특정 조건이 맞다면 while을 종료 - break
var i = 0;
while(true){
if( i >= 3 ) break;
i++;
print("i - $i");
}
for 루프 반복문 종료 - continue
var callbacks = ['a', 'b', 'c', 'd', 'e'];
for (var i = 0; i < callbacks.length; i++) {
if( i >= 3) continue;
print("for - ${callbacks[i]}");
}
switch and case
Dart의 switch 문은 정수, 문자열 또는 컴파일러 시간 상수(?, compile-time constants)를 비교함. 비교된 개체는 모두 동일한 클래스의 인스턴스여야 하며, 클래스가 재정의 되어서는 안됨.
▸ 같은 타입으로 비교하는 소리 같은데...
그리고 case 에서 break 를 사용하는 것을 원칙으로 한다.
var command = 'OPEN';
switch (command) {
case 'CLOSED':
executeClosed();
break;
case 'PENDING':
executePending();
break;
case 'APPROVED':
executeApproved();
break;
case 'DENIED':
executeDenied();
break;
case 'OPEN':
executeOpen();
break;
default:
executeUnknown();
}
다음 예제는 오류가 발생되는 예. case 안에 수행하는 내용이 존재하면 오류가 발생됨.
var command = 'OPEN';
switch (command) {
case 'OPEN':
executeOpen();
// ERROR: Missing break
case 'CLOSED':
executeClosed();
break;
}
하지만 비어 있는 경우는 사용할 수 있다.
var command = 'CLOSED';
switch (command) {
case 'CLOSED': // Empty case falls through.
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
또는 continue 문을 사용하여 진행할 수 있음.
▸ 테스트 해보지 않았으나, executeClosed()를 실행한 후에 nowClosed가 명시된 case 'NOW_CLOSED'를 수행하는 것으로 보임.
var command = 'CLOSED';
switch (command) {
case 'CLOSED':
executeClosed();
continue nowClosed;
// Continues executing at the nowClosed label.
nowClosed:
case 'NOW_CLOSED':
// Runs for both CLOSED and NOW_CLOSED.
executeNowClosed();
break;
}
assert
개발 환경에서 assert 문구를 사용함. assert( condition, optionalMessage);
참/거짓 조건에서 거짓인 경우 해당 부분에서 중단됨.
var text;
assert(text != null);
true 인 경우 그대로 진행됨
var text;
assert(text == null);
try-catch and throw
예외처리에 관한 내용.
throw 를 이용하여 예외상황을 만들 수 있음.
throw 'Out of llamas!';
try-catch 를 이용하여 예외가 발생된 코드를 처리하기 위해 사용. 이것도 다른 언어들과 거의 동일.
try {
breedMoreLlamas();
} on OutOfLlamasException {
// A specific exception
buyMoreLlamas();
} on Exception catch (e) {
// Anything else that is an exception
print('Unknown exception: $e');
} catch (e, s) {
// No specified type, handles all
print('Something really unknown: $e');
}
catch 상황에서 매개 변수를 넣을 수 있는데 수에 따라 다음과 같이 처리 됨.
매개변수 0. 아무것도 없음
매개변수 1. Exception 상세 내용
매개변수 2. StackTrace 객체
rethrow를 사용하면 exception 상황을 처리하고 중지되지 않고 진행되도록 한다.