관리 메뉴

나만을 위한 블로그

[Dart] 반복문 본문

Flutter

[Dart] 반복문

참깨빵위에참깨빵 2024. 8. 6. 01:10
728x90
반응형

아래 공식문서를 바탕으로 작성한다.

 

https://dart.dev/language/loops

 

Loops

Learn how to use loops to control the flow of your Dart code.

dart.dev

 

dart의 반복문은 3종류 있다.

 

  • for문
  • while
  • do-while

 

for문의 형태는 자바와 매우 비슷하다.

 

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

 

자바의 향상된 for문과 같은 형태로도 쓸 수 있다. for-in 루프라고 하는 듯한데, 차이라면 자바에선 콜론을 쓰지만 dart에선 in을 쓴다.

 

for (final candidate in candidates) {
  candidate.interview();
}

 

for-in 루프에서 패턴을 사용해 반복 중 얻은 값을 사용할 수도 있다.

 

void main() {
  List<Candidate> candidates = [
    Candidate(
      name: "a",
      yearsExperience: 1,
    ),
    Candidate(
      name: "b",
      yearsExperience: 2,
    ),
    Candidate(
      name: "c",
      yearsExperience: 3,
    ),
  ];
  
  for (final Candidate(:name, :yearsExperience) in candidates) {
    print('$name has $yearsExperience of experience.');
  }
}

class Candidate {
  final String name;
  final int yearsExperience;
  
  Candidate({
    required this.name,
    required this.yearsExperience,
  });
}

// a has 1 of experience.
// b has 2 of experience.
// c has 3 of experience.

 

더 많은 for-in 루프 예시를 확인하려면 컬렉션을 순회하는 문서를 참고한다.

 

https://dart.dev/libraries/collections/iterables

 

Iterable collections

An interactive guide to using Iterable objects such as lists and sets.

dart.dev

 

while은 그냥 자바, 코틀린과 똑같다. 사실 달라져봐야 뭐 크게 다를까 생각된다.

 

void main() {
  List<int> nums = [1, 2, 3, 4, 5];
  
  int index = 0;
  
  while (index < nums.length) {
    print(nums[index]);
    index++;
  }
}

// 1
// 2
// 3
// 4
// 5

 

do-while도 자바, 코틀린에서 자주 써봤다면 무리없이 쓸 수 있다.

 

void main() {
  int number = 0;
  
  do {
    print(number);
    number++;
  } while (number < 5);
}

// 0
// 1
// 2
// 3
// 4

 

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

 

반응형
Comments