
컬렉션, 숫자, 문자열 등을 순회할 때 사용
let names = ["Alex", "Brian", "John", "Jack"]
for name in names { } // name : "Alex", "Brian", "John", "Jack"
Dictionary, Set 등을 순회할 때는 순서가 보장되지 않음.
for i in 1...5 { } // i : 1, 2, 3, 4, 5
for j in 1..<5 { } // i : 1, 2, 3, 4
_ 키워드를 사용해 성능 향상을 기대할 수 있다.let base = 3
let power = 4
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) ^ \(power) = \(answer)")
// 3 ^ 4 = 81
stride(from:to:by:) 메서드로 범위와 증감을 설정할 수 있다.for i in stride(from: 100, to: 0, by: -10) { } // i : 100, 90, 80, ..., 30, 20, 10
for j in stride(from: 0, to: 60, by: 5) { } // j : 0, 5, 10, 15, ..., 45, 50, 55
while, repeat-while 문while condition {
statements
}
repeat {
statements
} while condition
// do-while과 유사한 구문
if-else 문if condition1 {
statements1
} else if condition 2 {
statements2
} else {
statements3
}
switch 문switch value {
case value1:
statement1
case value2, value3:
statement2
default:
statement3
}
안에 있는 case들이 switch 에 주어진 값을 모두 검사할 수 있어야 한다.
default를 사용하거나
주어진 값이 enum이면 해당 case 들을 모두 적어주거나
튜플이면 모든 튜플을 검사할 수 있어야 함.
No Implicit Fallthrough
Swift는 C, Objective-C와 다르게 case 문이 종료된 후 break를 적지 않아도 switch 문을 빠져 나간다.
Interval Matching
숫자의 범위를 조건으로 사용할 수 있다.
let count = 5
switch count {
case ..<0:
print("under 0")
case 0:
print("0")
case 1..<10:
print("1 ~ 9")
case 10..<100:
print("10 ~ 99")
default:
print("over 100")
}
// 1 ~ 9
_ 키워드는 어느 것이나 매칭된다는 뜻let point = (1, 1)
switch point {
case (0, 0):
print("Origin")
case (_, 0):
print("On the x-axis")
case (0, _):
print("On the y-axis")
case (-2...2, -2...2):
print("Inside the box")
default: // -> case (_, _): 으로도 사용 가능
print("Outside of the box")
}
// Inside the box
case에 정의하고, 그 정의된 상수를 case에서 사용할 수 있다.switch point {
case (let x, 0):
print("*, 0") // point가 (n, 0)이면 x는 n이 된다. (n: Int)
case (0, let y):
print("0, *") // point가 (0, n)이면 y는 n이 된다. (n: Int)
case let (a, b):
print("\(a), \(b)") // point가 (n, m)이면 a는 n, b는 m이 된다. (n, m: Int)
}
wherecase, for-in 등에 where 조건을 사용할 수 있다.let point = (1, -1)
switch point {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
// (1, -1) is on the line x == -y
for i in 1...10 {
for j in 1...10 where i == j {
print("\(i) \(j)")
}
}
// 1 1
// 2 2
// 3 3
// ...
// 10 10
continue, break
C의 기능과 동일
fallthrough
switch문의 자동 break를 막는 역할
다음 case의 조건을 검사하지 않고 무조건 실행함.
let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += " a prime number, and"
fallthrough // switch를 빠져나가지 않고 다음 구문을 실행
case -1:
description += " also"
fallthrough
default:
description += " an integer."
}
// The number 5 is a prime number, and also an integer.
// case -1:, default: 에 원래 걸리지 않지만, fallthrough의 작용으로 case를 모두 실행
outer: for i in 1...3 {
for j in 1...3 {
print("\(i) \(j)")
if i == 2 && j == 2 { break outer }
}
}
// 1 1
// 1 2
// 1 3
// 2 1
// 2 2
guard-elseguard를 이용해 특정 조건을 만족하지 않으면 이후 코드를 실행하지 않도록 할 수 있다.
옵셔널 언래핑 등에 자주 사용
else 문 내부에는 무조건 코드 블럭을 탈출하는 구문을 작성해야 함.
func checkEmailValid(emailParam: String?) {
guard let email = emailParam else {
print("emailParam is nil.")
return
}
...
}
var inputEmail: String?
checkEmailValid(inputEmail)
// "emailParam is nil."
플랫폼과 특정 버전을 확인하는 구문을 제공하고,
이를 통해 다른 버전을 사용하는 기기에 대한 처리를 따로 할 수 있다.
if #available(iOS 10, macOS 10.12, *) {
...
} else {
...
}