for-in문 (for-in loop)
for-in문은 배열, 숫자, 문자열을 순서대로 순회하기 위해 사용한다.
let names = ["Yeo", "Lee", "Choi"]
for name in names {
print("Hello, \(names)!")
}
// Hello, Yeo!
// Hello, Lee!
// Hello, Choi!
let setNames: Set = ["Yeo", "Kim", "Kang"]
for name in setNames {
print(name)
}
// Kim
// Kang
// Yeo
let dictName: [String: Int] = ["Yeo": 1, "Lee": 2]
for (key, value) in dictName {
print(key, value)
}
// Lee 2
// Yeo 1
✔️ 위의 예제와 같이 for-in문을 이용해서 set과 dictionary도 순회하며 제어할 수 있다.
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// Prints "3 to the power of 10 is 59049"
✔️ 위의 예제와 같이 for-in문을 순서대로 제어할 필요가 없다면, 변수 자리에 _키워드를 사용하면 성능을 높힐 수 있다.
let times = 12
for tickMark in 0..<times {
print(tickMark+1)
}
// 1
// 2
// ..
// 12
✔️ 위의 예제와 같이 범위 연산자와 함께 사용할 수 있다.
let interval = 5
for tickMark in stride(from:0, to: 15, by: interval) {
print(tickMark)
}
// 0
// 5
// 10
for tickMark in stride(from:0, through: 15, by: interval) {
print(tickMark)
}
// 0
// 5
// 10
// 15
✔️ 위의 예제와 같이 stride() 함수를 이용할 수 있다.
while문 (while loop)
while문은 조건(condition)이 거짓일때까지 구문을 반복한다.
while condition {
statements
}
var condition1 = true
var a = 0
while condition1 {
a += 1
print("a = \(a)")
if(a==5) { condition1 = false }
}
print("end while")
// a = 1
// a = 2
// a = 3
// a = 4
// a = 5
// end while
Repeat-while문 (Repeat-while loop)
Repeat-while문은 구문을 최소 한번 이상 실행하고 while 조건이 거짓일 때까지 반복한다.
repeat {
statments
} while condition
var condition1 = false
var a = 0;
repeat {
a += 1
print("a = \(a)")
} while condition1
print("end repeat")
// a = 1
// end repeat
조건적 구문 (Conditional Statements) - if문
1️⃣ if문
var a = 10
if a >= 10 {
print("true")
}
// true
2️⃣ if-else문
var a = 10
if a>10 {
print("true")
} else {
print("false")
}
// false
3️⃣ if-else if문
var num = 15
if num > 10 {
print("\(num) > 10")
} else if num < 10 {
print("\(num) < 10")
}
// 15 > 10
4️⃣ if-else if-else문
var num = 15
if num > 20 {
print("\(num) > 20")
} else if num < 10 {
print("\(num) < 10")
} else {
print("i don't know")
}
// i don't know
조건적 구문 (Conditional Statements) - switch문
let point: Character = "B"
switch point {
case "A" : print("point A")
case "B" : print("point B")
case "C" : print("point C")
default : print("point F")
}
// point B
✔️ 위의 예제와 같이 스위프트에서는 switch에서는 break를 적지 않아도 특정 case가 완료되면 자동으로 switch구문을 빠져 나오게 된다. break가 필수적이지는 않지만 case안에 특정 지점에서 멈추도록 하기 위해 break를 사용할 수 있다.
let point: Character = "a"
switch point {
case "A", "a" : print("point A")
case "B", "b" : print("point B")
case "C", "c" : print("point C")
default : print("point F")
}
// point A
✔️ 위의 예제와 같이 case안에 콤마(,)로 구분해서 복수의 case 조건을 사용할 수 있다.
let num = 30
switch num {
case 0..<10 : print("range of \(num) is 0~9")
case 10..<20 : print("range of \(num) is 10~19")
case 20..<31 : print("range of \(num) is 20~30")
default : print("range over")
}
//range of 30 is 20~30
✔️ 위의 예제와 같이 숫자의 특정 범위를 조건으로 사용할 수 있다.
let somePoint = (1, 10)
switch somePoint {
case (0, 0):
print("\(somePoint) is at the origin")
case (_, 0):
print("\(somePoint) is on the x-axis")
case (0, _):
print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
print("\(somePoint) is inside the box")
default:
print("\(somePoint) is outside of the box")
}
// (1, 10) is outside of the box
✔️ 위의 예제와 같이 튜플을 조건으로 사용할 수 있다.
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
// on the x-axis with an x value of 2
let anotherPoint2 = (5, 2)
switch anotherPoint2 {
case (let x, 2):
print("on the x-axis with an x value of \(x)")
case (2, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
// somewhere else at (5, 2)
✔️ 위의 예제와 같이 특정 x,y 값을 각각 다른 case에 정의하고 그 정의된 상수를 또 다른 case에서 사용할 수 있는 기법을 값 바인딩이라 하는데, switch에서는 값 바인딩을 사용할 수 있다.
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
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
✔️ 위의 예제와 같이 case에 where문을 사용할 수 있다.
let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
print("On an axis, \(distance) from the origin")
default:
print("Not on an axis")
}
// On an axis, 9 from the origin
✔️ 위의 예제와 같이 혼합 케이스에서도 값-바인딩을 사용할 수 있다.
제어 전송 구문 (Control Transfer Statements)
1️⃣ continue문 : 현재 loop를 중지하고 다음 loop를 수행하게 한다.
for i in 1..<11 {
if i % 2 == 1 {
continue
}
print(i)
}
//2,4,6,8,10
2️⃣ break문 : 전체 제어문의 실행을 즉각 중지 시킨다.
let points = ["B", "C", "B", "A"]
var count = 0
for point in points {
if point == "A" {
break
}
count += 1
}
print(count)
// 3
3️⃣ fallthrough문 : 이후의 case에 대해서도 실행하게 한다. 스위프트에서는 한번 특정 case를 완료하면 자동으로 switch구문을 빠져나오게 되는데 fallthrough를 사용하면 자동으로 break가 사용되는 것을 막는 효과를 가져온다.
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 also"
fallthrough
default:
description += " an integer."
}
print(description)
// "The number 5 is a prime number, and also an integer."
⚠️ fallthrough는 case 조건을 확인하지 않고 그냥 다음 case를 실행한다.
레이블 구문 (Labeled Statements)
label 이름과 while 조건을 넣어 특정 구문을 실행하는 구문으로 사용할 수 있다.
label name : while condition {
statements
}
var point = "A"
labeleEx: while true {
switch point {
case "A" : break labeleEx
default : continue
}
}
print("labele end")
// labele end
이른 탈출 (Early Exit)
guard 조건 else {
// 조건이 false이면 실행
return || throw
}
✔️ guard문을 이용해 특정 조건을 만족하지 않으면 이 후 코드를 실행하지 않도록 방어코드를 작성할 수 있다.
✔️ if문과의 차이점은 if문은 "~면 ~해라"의 실행 구문이지만, guard는 "~아니면 끝내라"라는 의미이다.
var con1 = true
var con2 = true
func guardTest() {
guard con1, con2 else {
return print("guarding")
}
print("guard failure")
}
guardTest()
// guard failure
'Swift > Swift 기본기' 카테고리의 다른 글
06. 클로저 (Closures) (0) | 2023.03.18 |
---|---|
05. 함수 (Functions) (0) | 2023.03.18 |
03. 콜렉션 타입 (Collection Types) (0) | 2023.03.17 |
02. 문자열과 문자 (Strings and Characters) (0) | 2023.03.16 |
01. 기본 연산자 (Basic Operators) (1) | 2023.03.15 |