[swift] 반복문 (loops)

Snyong·2023년 9월 28일

swift

목록 보기
4/10
post-thumbnail

for loops

  • for loop를 이용해서 array, range를 돌면서 코드를 반복 수행할 수 있음
let numRange = 1...10 // 1~10

for num in numRange{
    print("num is \(num)")
}


let names = ["John", "Kevin", "Jason"]

for name in names {
    print("name is \(name)")
}

while loops

  • while loop를 이용하면 특정 조건을 만족할때까지 코드를 반복 수행할 수 있음
var num1 = 1

while num1 < 20 {
    print(num1)
    num1 += 1
}

print("조건 만족하지 않아 탈출")

You mentioned (num1<20) and asked why it’s not necessary to use parentheses around the condition. In Swift, you don’t need to enclose the condition within parentheses in control flow statements like while, if, for-in, etc. Swift’s syntax is designed to be clear and concise, and it allows you to write conditions without parentheses. Using parentheses is allowed, but it’s not required, and many Swift programmers omit them for brevity and readability.

repeat loops

  • repeat loop를 이용하면 특정 조건을 만족할때까지 코드를 반복 수행할 수 있음
  • 최초 1회 수행 후 조건 체크 (do-while과 비슷)
var num2 = 1

repeat {
    print(num2)
    num2 += 1
} while num2 <= 20

print("조건을 만족하지 않아 탈출")

exiting & skipping

  • loop를 돌다 탈출하고 싶을때는 break 키워드 이용
  • loop를 돌다 스킵하고 싶을때는 continue 키워드 이용

0개의 댓글