![Swift : 기초문법 [Repeat 루프] Swift : 기초문법 [Repeat 루프]](https://blog.kakaocdn.net/dn/LKnZV/btrpU082JlF/0R7R7GgbYIgcSRkAYj3dW1/img.png)
Reapeat 루프
세 번째 루프 작성 방법은 자주 사용되지 않지만 아주 쉽습니다. Repeat
루프라고 불리며, 마지막에 확인할 조건을 제외하고 While
루프와 동일합니다.
swift
UNFOLDEDvar number = 1 repeat { print(number) number += 1 } while number <= 20 print("준비가 됐다면 시작할께요!") //20가지 카운트 후, 텍스트 출력
만약 while
문에 false
가 있고 출력될 텍스트가 있다면 Xcode
는 아무것도 출력하지 않을것입니다.
swift
UNFOLDEDwhile false { print("This is false") }
하지만 Repeat
문을 사용한다면 처음에 텍스트를 출력 후, while
문을 실행하기때문에 텍스트가 한 번 출력됩니다.
swift
UNFOLDEDrepeat { print("This is false") } while false //This is false
예시
swift
UNFOLDEDlet numbers = [1, 2, 3, 4, 5] var random: [Int] repeat { random = numbers.shuffled() } while random == numbers //랜덤값 무자기 출력 //3, 2, 4, 5, 1
swift
UNFOLDEDvar countdown: Int = 5 repeat { print("\(countdown)...") countdown -= 1 } while countdown > 0 print("Lift off!")
swift
UNFOLDEDvar frogs = 4 repeat { for _ in 1...frogs { print("repeat문 안에 for문!") } } while false
swift
UNFOLDEDvar scales = ["A", "B", "C", "D", "E"] var scaleCounter = 0 repeat { print("Play the \(scales[scaleCounter]) scale") scaleCounter += 1 } while scaleCounter < 3 //Play the A scale //Play the B scale //Play the C scale
잘못된 예시
swift
UNFOLDEDlet people = 0 repeat { people += 1 print("There's space another person") } while people < 10 print("We're full!") //상수인 people을 수정하려고 합니다.
Repeat문 TEST : 문제를 풀려면 이곳을 클릭해주세요.
읽어주셔서 감사합니다🤟
잘못된 내용이 있으면 언제든 피드백 부탁드립니다.
'SWIFT > Grammar' 카테고리의 다른 글
Swift : 기초문법 [중첩된 루프에서 Break] (0) | 2021.02.21 |
---|---|
Swift : 기초문법 [Break Loop / 항복건너뛰기(Continue)] (0) | 2021.02.21 |
Swift : 기초문법 [While 루프] (0) | 2021.02.21 |
Swift : 기초문법 [For 루프] (1) | 2021.02.21 |
Swift : 기초문법 [스위치 - Switch(break/fallthrough)] (2) | 2021.02.20 |