[ios/swift]Repeating Tasks(for-in,while,repeat-while)

감자맨·2022년 7월 30일
0

swift

목록 보기
4/14
post-thumbnail

📒📕 📗📘📙📚📖 swift 문법을 공부하자!📒📕 📗📘📙📚📖

반복문

for-in

for-in 반복 구문 ***은 반복적인 데이터나 시퀀스를 다룰 때 많이 사용한다.

for 임시 상수 in 시퀀스 아이템 {
    실행코드
}

예시

for i in 0...2{
    print(i)
}
// 0
// 1
// 2
for i in 0...5{
    if i.isMultiple(of: 2) {
        print(i)
        continue   // continue 키워드를 사용하면 바로 다음 시퀀스로 건너뛴다.
    }
    print("\(i) == 홀수")
}

//0
// 1 == 홀수
// 2
// 3 == 홀수
// 4
// 5 == 홀수

💡 break문과 continue 차이점 break문은 조건문도 빠져나가면서 반복문 자체도 탈출하고 끝이나지만, continue문은 해당 '조건문만' 실행하지 않고, 반복문은 이어서 실행하는 제어문이다.

while

while 반복문도 for-in과 마찬가지로 continue. break 등의 제어 키워드 사용이 가능하다.

var counter = 0
 
while counter <= 100 {
    print(counter)
    counter += 1
    
    if counter == 10{
        break
    }
    
}
print("stop")
//0
//1
.
.
.
//9
//stop

repeat - while

repeat - while 반복문은 다른 프로그래밍 언어의 do-while 구문과 크게 다르지 않다. repeat 블록의 코드를 최초 1회 실행한 후, while 다음의 조건이 성립하면 블록 내부의 코드를 반복 실행한다.
var names: [String] = ["Jenny", "Joker", "yoojin"]

repeat {
    print("Good bye \(names.removeFirst())")
    // removeFirst()는 요소를 삭제함과 동시에 삭제한 요소를 반환한다.
} while names.isEmpty == false

// Good bye Jenny
// Good bye Joker
// Good bye yoojin
profile
나는 코딩하는 감자다!

0개의 댓글