2.7 Loops

Joohyun·2022년 4월 7일
0

For Loops

  • for-in구문으로 해당 범위만큼 반복문을 수행한다.
for index in 1...5 {
	print(index)
}
// console
1
2
3
4
5
  • 반복횟수를 for문 내부에서 사용하지 않을 경우 _로 처리하여 값이 할당되지 않도록 한다.
for _ in 1...3 {
	print("Hello!")
}
// console
Hello!
Hello!
Hello!

Range Operator

1. closed range operator

// x <= i <= y
for i in x...y { ... }

2. half-open range operator

// x <= i < y
for i in x..<y { ... }
  • 예시
let animals = ["Lion", "Tiger", "Bear"]

for index in 0..<animals.count {
	print("\(index): \(animals[index])")
}
// console
0: Lion
1: Tiger
2: Bear

Array

let names = [Joseph,Cathy,Winston]

for name in names {
  print(name)
}
// console
Joseph
Cathy
Winston

String

for letter inABCD{
  print(letter)
}
// console
A
B
C
D

enumerated()

  • Array, Stringenumerated()를 사용하면 인덱스와 각 원소를 튜플로 리턴한다.
for (index, letter) inABCD.enumerated() {
  print(”\(index): \(letter))
}
// console
0: A
1: B
2: C
3: D

Dictionary

  • Dictionary는 순서가 존재하지 않으므로 인덱스 대신 key, value값에 접근할 수 있다.
let vehicles = [”unicycle”: 1, “bicycle”: 2, “tricycle”: 3, 
“quad bike”: 4] 
for (vehicleName, wheelCount) in vehicles {
  print(”A \(vehicleName) has \(wheelCount) wheels”)
}
// console
A unicycle has 1 wheels
A bicycle has 2 wheels
A tricycle has 3 wheels
A quad bike has 4 wheels

While Loops

  • 조건이 true이면 계속 loop를 반복하고 false가 되면 loop를 빠져나간다.

  • 조건 내부의 값을 변경해주는 로직이 존재하지 않으면 무한루프를 돌 수 있다.

var numberOfLives = 3
 
// numberOfLives가 0이 되거나 0보다 작아질 때까지 반복한다.
while numberOfLives > 0 {

  // numberOfLives값을 변경해주는 로직이 존재해야 한다.
  playMove()
  updateLivesCount()
}

Repeat-While Loops

  • while문과 비슷하지만 1번은 무조건 실행하고, 그 후 조건을 체크한다.
var steps = 0
let wall = 2
 
repeat {
  print("Step")
 
  steps += 1
} while steps < wall
// console
Step
Step

break

  • loop 도중에 빠져나와 loop문 수행을 종료한다.
for counter in -3...3 {
  print(counter)
  
  // counter가 0이 되면 for문을 종료한다.
  if counter == 0 {
    break
  }
  
}
// console
-3
-2
-1
0

continue

  • 진행 중이던 해당 loop문을 중단하고, 다시 loop의 처음으로 가서 다음 반복을 수행한다.
for person in people {

  // 19세 이상의 사람들에게만 이메일을 전송한다.
  if person.age < 18 {
    continue
  }
 
  sendEmail(to: person)
}
profile
IOS Developer

0개의 댓글