[Swift 기본 문법] 제어구문 - 반복문 (for-in, while, repeat-while)

Ryan (Geonhee) Son·2021년 3월 6일
0
post-thumbnail

본 Lecture Note는 yagom.net의 '스위프트 기초' 강의를 수강하고 작성하였습니다.

Swift의 반복문을 알아보겠습니다. 반복문은 Collection 타입과 많이 사용됩니다.

for-in

다른 프로그래밍 언어의 for-each 구문과 유사합니다. for 뒤에 iteration으로 들어올 item 이름을 적어주고 in 뒤에 iteration의 대상이 될 collection 타입을 적어주시면 됩니다.

var integers = [1, 2, 3]
let people = ["Ryan": 10, "Kio": 15, "Steven": 12]

for item in items {
  code
}

for integer in integers {
  print(integer)
}

// Dictionary의 item은 key와 value로 구성된 튜플 타입입니다.
for (name, age) in people {
  print("\(name): \(age)")
}

while

다른 프로그래밍 언어의 while과 유사합니다. 조건은 소괄호 생략이 가능하지만 중괄호는 생략이 불가능합니다. 조건은 조건문과 동일하게 Bool 타입만 받아들일 수 있습니다.

while condition {
  code
}

while integers.count > 1 {
  integers.removeLast()
}

repeat-while

다른 프로그래밍 언어의 repeat-do 구문과 유사합니다. repeat 구문의 뒷 중괄호에 실행 구문을 while에서 조건을 체크하여 해당하는 경우 반복하는 형식입니다. do라는 구문을 사용하지 않은 이유는 do가 Swift의 에러 처리(error handling)에 사용되는 키워드이기 때문입니다.

repeat {
  code
} while condition

repeat {
  integers.removeLast()
} while integers.count > 0
profile
합리적인 해법 찾기를 좋아합니다.

0개의 댓글