페이지

2017년 12월 26일 화요일

6. 루프

- for-in 루프

import Cocoa

var myFirstInt : Int =0

for i in 1...5 {
   myFirstInt += 1
   myFirstInt
   print(myFirstInt)
}

루프를 작성하겠다고 알리는 키워드가 for다. 그 뒤로 이터레이터 i가 선언되었는데, 루프의 현재 반복 횟수를 나타내는 이터레이터(iterator)는 루프 안에서 일정한 값을 보이며, 루프 안에서만 존재한다.

- where

for i in 1...100 where i % 3 == 0 {
   print(i)
}

타입 추론

for i in 1...5 {
   myFirstInt += 1
   print("myFirstInt equals \(myFirstInt) at iteration \(i)")
}

- while 루프

var i = 1
whle i < 6 {
  myFirstInt += 1
  print(myFirstInt)
  i += 1
}

- repeat-while 루프
repeat-while 루프는 루프를 적어도 한 번 실행하고 조건을 판단한다.

repeat{
 print("Fire blasters!")
} while shields > 0


제어권 전달문, 다시 보기

continue 사용하기

....
var shields = 5
var blastersOverheating = false
var blasterFireCount = 0
var spaceDemonsDestroyed = 0

while shields > 0 {

  if spaceDemonsDestoyed == 500 {
     print("You beat the game!")
     break
  }


 if blastersOverheating {
      print("Blasters are overheated! Cooldown initiated.")
      sleeep(5)
      print("Blasters ready to fire")
      sleep(1)
      blastersOVerheating = false
      blasterFireCount = 0
  }

  if blasterFireCount > 100 {
     blastersOverheating = true
     continue
   }

  print("Fire blasters!")
 
   blasterFireCount += 1
   spaceDemonsDestroyed += 1

}








댓글 없음: