250x250
반응형
05-11 18:03
Today
Total
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Notice
Recent Posts
Recent Comments
Link
Archives
관리 메뉴

Bill Kim's Life...

[Dart] Control flow statements(제어문) 본문

CS(컴퓨터 과학)/Dart

[Dart] Control flow statements(제어문)

billnjoyce 2020. 8. 20. 11:12
728x90
반응형
Dart 언어에서의 Control flow statements(제어문)에 대하여 살펴봅니다.

 

 

#. 구독 대상

  • Dart 언어를 처음 접하시면서 공부해보고 싶으신 분
  • 플러터(Flutter) 개발에 관심이 있어나 해보고 싶으신 분
  • 멀티 플랫폼 모바일 앱 개발을 시작하고 싶으신 분
  • 기타 소프트웨어 개발과 지식에 관심이 있으신 모든 분들

 

 


 

제어문

 

Dart에서도 아래와 같은 다양한 형태의 제어문을 제공합니다.

오늘은 아래의 다양한 제어문에 대해서 하나하나씩 코드 예제를 통해서 기본적인 사용법에 대하여 살펴보겠습니다.

 

  • if and else
  • for loops
  • while and do-while loops
  • break and continue
  • switch and case
  • assert

 

 


 

 

If and else

일반적인 Java와 비슷한 형태로 사용할 수 있습니다.

if (isRaining()) {
  you.bringRainCoat();
} else if (isSnowing()) {
  you.wearJacket();
} else {
  car.putTopDown();
}

 

 


 

 

For loops

For문은 일반적인 변수 선언 및 조건문 비교로도 하며 collection 객체 사용시에는 in 키워드와 함게 사용도 가능합니다.

또한 클로저 형태의 람다 함수와 함께 forEach 활용도 가능합니다.

 

혹시 객체가 Iterable라면 shorthand 방식의 함수를 이용해서 continue를 다른 방식으로 표현할 수 있습니다.

해당 방식의 구현은 Iterable where forEach 함수를 이용합니다.

 

하지만 코드가 간편해지는 장점은 있지만 성능 하락의 문제점이 있으므로 최적화 또는 많은 데이터를 처리할때는 함수를 이용하지 말고 전통적인 (for,while) 반복문을 사용하는 것을 권장합니다.

var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
  message.write('!');
}

var callbacks = [];
for (var i = 0; i < 2; i++) {
  callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());

var collection = [0, 1, 2];
for (var x in collection) {
  print(x); // 0 1 2
}

// continue를 통한 반복문 skip 또한 가능
for (int i = 0; i < candidates.length; i++) {
  var candidate = candidates[i];
  if (candidate.yearsExperience < 5) {
    continue;
  }
  candidate.interview();
}

// Collection 객체에서의 조건문 형식의 반복문 사용 가능
candidates
    .where((c) => c.yearsExperience >= 5)
    .forEach((c) => c.interview());

 

 

 


 

 

While and do-while

While문은 아래와 같이 Java와 거의 같은 형태로의 사용이 가능합니다.

while (!isDone()) {
  doSomething();
}

while (true) {
  if (shutDownRequested()) break;
  processIncomingRequests();
}

do {
  printLine();
} while (!atEndOfPage());

 

 

 


 

 

Switch and case

Switch문 또한 거의 C나 Java와 유사한 형태로 사용할 수 있습니다.

다만 한 case에서 break 문을 생략시에는 에러를 볼 수 있습니다. 다만 연속된 case 선언을 통하여 다수의 조건을 만들 수는 있습니다.

다만 break문을 생략하고 다수의 조건을 조합하여 실행하고 싶을 경우에는 continue 문을 활용하여 사용할 수 있습니다.

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();
}

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;
}

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문은 개발에서의 디버깅 용도로 사용하는 제어문으로서 상용 버전의 빌드(release)에서는 아무런 영향을 주지 않는 제어문입니다. 사용은 asset문에 조건문 또는 추가 메시지를(assert(condition, optionalMessage)) 조합하여 사용할 수 있습니다.

 

해당 조건문을 만족하지 않을 경우 AssertionError 예외를 호출(메세지)하게 됩니다.

// Make sure the variable has a non-null value.
assert(text != null);

// Make sure the value is less than 100.
assert(number < 100);

// Make sure this is an https URL.
assert(urlString.startsWith('https'));


assert(urlString.startsWith('https'), 'URL ($urlString) should start with "https".');

 

 

 


 

 

 

지금까지 Dart 언어에서의 다양한 Control flow statements(제어문)에 대해서 살펴보았습니다.

 

감사합니다.

 

 

 

 

 

 

 

 

 


[참고 자료(References)]

 

[1] A tour of the Dart language : dart.dev/guides/language/language-tour

[2] flutter에서 사용하는 dart 언어의 제어문 알아보기 : minwook-shin.github.io/flutter-dart-lang-tour-control-flow-statements/

[3] Google의 새로운 프로그래밍 언어 Dart 강좌 - 제어문과 예외처리 : miruel.tistory.com/entry/Google의-새로운-프로그래밍-언어-Dart-강좌-제어문

[4] 다트(Dart) 훑어보기 -2 : 제어문 / 반복문 : jvvp.tistory.com/1140

[5] Dart - 언어 시작하기 ( 반복문, 제어문) - 난장 : naan.co.kr/109

728x90
반응형

'CS(컴퓨터 과학) > Dart' 카테고리의 다른 글

[Dart] Exceptions(예외 처리)  (0) 2020.08.20
[Dart] Functions(함수)  (0) 2020.08.20
[Dart] Operators(연산자)  (0) 2020.08.19
[Dart] Collection : List & Set & Map  (0) 2020.08.19
[Dart] Variables(변수)  (0) 2020.08.19
Comments