100 days of swiftui: 6
https://www.hackingwithswift.com/100/swiftui/6
let colors = ["red", "green", "yellow", "blue"]
for color in colors {
print("This is \(color).")
}
for i in 1..<5 {
print("This is number \(i)")
}
for loop를 통해 in
뒤의 범위만큼 반복문을 실행할 수 있다. 범위는 1...5
1부터 5까지, 리스트 colors
의 요소만큼, 1..<5
1부터 5의 전까지(정수 4까지)로 설정할 수도 있다.
❗️범위를 tuple로 설정할 수 없다.
코드 파일
https://github.com/soaringwave/Ios-studying/commit/25be85336c04478d201759dacb506a706c7fa53f
let winner = 1
var picker = 0
while picker != winner {
print("Sorry, \(picker) is not the winner!")
picker = Int.random(in: 1...10)
}
print("Now, 1 is the winner!")
while 뒤의 조건문이 참인 동안 {}사이의 문장을 수행한다.
코드 파일
https://github.com/soaringwave/Ios-studying/commit/5d12269db309c083d8927f4f74d562ddf12701db
break
는 남은 iteration을 중단하고 해당 반복문을 벗어나게 한다.
let filenames = ["work.txt", "sophie.jpg", "me.jpg", "logo.psd"]
for filename in filenames {
if filename.hasSuffix(".jpg") {
print("First Founded picture: \(filename)")
break
}
}
결과:
First Founded picture: sophie.jpg
continue
는 해당 줄 아래의 코드를 실행하지 않고 다음 iteration으로 넘긴다.
for filename in filenames {
if !filename.hasSuffix(".jpg"){
continue
}
print("Founded picture: \(filename)")
}
결과:
Founded picture: sophie.jpg
Founded picture: me.jpg
코드 파일
https://github.com/soaringwave/Ios-studying/commit/861529fedcc5d96146d1f1c1bd7ddc5daa7c593f