Swift 에서는 while loop, if guard, switch, for-in 문 등 많은 제어문을 제공한다.
for-in loops는 배열, 숫자, 문자열을 순서대로 순회(iterate)하기 위해 사용한다.
튜플을 순회하며 제어할 수도 있다.
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
// ants have 6 legs
// spiders have 8 legs
// cats have 4 legs
사전에 담긴 콘텐츠는 정렬이 되지 않은 상태이기 때문에 사전에 넣었떤 순서대로 순회되지 않는다.
숫자 범위를 지정해 순회할 수 있다.
for index in 1...5 {
print("hi")
}
순서가 상관없다면 변수자리에 _ 를 사용해 성능을 높이자.
for _ in 1 ... 10 {
print("hi")
}
범위 연산자와 함께 사용가능하다.
for tickMark in 0..<minutes {
}
stride(from:to:by:) 함수와 함께 사용가능하다.
for tickMark in stride(from: 0, to:minutes, by:minuteInterval) {
}
Swift에서는 while과 repeat-while 를 지원한다.
while condition {
statements
}
repeat {
statements
} while condition
Swift에서는 if 와 switch 두 가지의 조건 구문을 제공한다.
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
print("It's really warm. Don't forget to wear sunscreen.")
} else {
print("It's not that cold. Wear a t-shirt.")
}
// Prints "It's really warm. Don't forget to wear sunscreen."
let someCharacter: Character = "z"
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
// Prints "The last letter of the alphabet"
Swift 에서는 break 를 적지 않아도 특정 case가 완료되면 자동으로 Switch 를 빠져 나오게 된다.
case 안에 최소 하나의 실행 구문이 반드시 있어야 한다.
복수의 case 조건을 혼합할 수 있다.
case "a", "A":
print("The letter A")
숫자의 특정 범위를 조건으로 사용할 수 있다.
case 1..<5:
naturalCount = "a few"
튜플을 조건으로 사용할 수 있다.
case (0, 0):
print("\(somePoint) is at the origin")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
case let (x, y) where x == y:
코드를 계속 진행할지 말지를 결정하거나 실행되는 코드의 흐름을 바꾸기 위해서 사용한다.
continue, break, fallthrough, return, throw
현재 loop를 중지하고 다음 loop을 수행하도록 한다.
전체 제어문의 실행을 즉각 중지시킨다.
이후의 case에 대해서도 실행하게 한다.
case 조건을 확인하지 않고 그냥 다음 case 를 실행하게 만든다.
label name: while condition {
statements
}
Swift에서는 기본으로 특정 플랫폼과 특정 버전을 확인하는 구문을 제공해준다.
if #available(platform name, version ..., *) {
statements to execute if the APIs are available
} else {
fallback statements to execute if the APIs are unavailable
}