조용한 담장

Dart : Control flow statements 본문

Dart

Dart : Control flow statements

iosroid 2019. 9. 17. 17:05

Dart language tour 에서 예제 코드만 긁어서 모아 보았다.

// if else
if (isRaining()) {
  you.bringRainCoat();
} else if (isSnowing()) {
  you.wearJacket();
} else {
  car.putTopDown();
}
// for loop
var message = StringBuffer('Dart is fun');
for (var i = 0; i < 5; i++) {
  message.write('!');
}
// closure in for loop, forEach()
var callbacks = [];
for (var i = 0; i < 2; i++) {
  callbacks.add(() => print(i));
}
callbacks.forEach((c) => c());
// for-in iterable classes
var collection = [0, 1, 2];
for (var x in collection) {
  print(x); // 0 1 2
}
// while
while (!isDone()) {
  doSomething();
}
// do-while
do {
  printLine();
} while (!atEndOfPage());
// break and continue
while (true) {
  if (shutDownRequested()) break;
  processIncomingRequests();
}
for (int i = 0; i < candidates.length; i++) {
  var candidate = candidates[i];
  if (candidate.yearsExperience < 5) {
    continue;
  }
  candidate.interview();
}
// using Iterable (where(), forEach())
candidates
    .where((c) => c.yearsExperience >= 5)
    .forEach((c) => c.interview());
// switch and case
var command = 'OPEN';
switch (command) {
/*
  case 'OPEN':
    executeOpen();
    // ERROR: Missing break

*/
  case 'CLOSED':
    executeClosed();
    break;
  case 'OPEN':
    executeOpen();
    break;
  default:
    executeUnknown();
/*
  case 'CLOSED': // Empty case falls through.
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
*/
}
// continue and label
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(text != null);
assert(number < 100);
assert(urlString.startsWith('https'));
assert(urlString.startsWith('https'),
    'URL ($urlString) should start with "https".');

'Dart' 카테고리의 다른 글

Dart : Class  (0) 2019.10.02
Dart : Exceptions  (0) 2019.09.20
Dart : Operators  (0) 2019.09.17
Dart 2.5  (0) 2019.09.11
Dart : Functions  (1) 2019.08.07
Comments