반복문 (for, switch)

CHOI·2021년 5월 25일
0

Swift

목록 보기
8/10
post-thumbnail

1. for 구문

기본적으로 다른 언어에서의 for 반복문과 유사하다.

var integers = [1, 2, 3]
let people = ["yagom": 10, "eric": 15, "mike": 12]

for integer in integers {
    print(integer)
}

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

Dictionary에 경우 item자리에 튜플 타입으로 받기 때문에 두개의 item을 지정해주면 된다.

2. while 구문

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

while문의 조건부분은 앞서 if문에서도 확인했듯이 Boolen타입이 와야한다.

만약 정수 1 과 같이 다른 타입이 올 경우 오류가 발생한다.

3. repeat - while 구문

repeat {
    integers.removeLast()
} while integers.count > 0

기존의 다른언어에서의 do - while 구문과 유사하다. (그러나 do 를 사용하지 않는 이유는 swifth에서는 오류처리 부분에서 do가 다른 목적으로 사용되기 때문이다.)

먼저 repeat구문이 반복 실행된 다음에 while 구문을 체크하여 조건에 만족되면 다시 repeat구문이 실행된다.

profile
벨로그보단 티스토리를 사용합니다! https://flight-developer-stroy.tistory.com/

0개의 댓글

Powered by GraphCDN, the GraphQL CDN