분기처리(Branch)란?
분기처리는 프로그램이 조건에 따라 다른 동작을 수행하도록 만드는 것으로, 실행 흐름을 조건에 따라 나누는 제어 구조를 의미합니다. 특정 조건이 참 혹은 거짓인지에 따라 서로 다른 코드 블록을 실행하거나 건너뛰게 만드는 방식입니다.
분기처리의 주요 목적
- 유연한 논리 처리를 가능케 하여 다양한 상황에 대처할 수 있습니다.
- 프로그램이 결정적인 작업을 수행할 수 있도록 심사합니다.
Swift에서의 분기처리
Swift의 official document에서는 분기처리를 아래와 같이 서술하고 있습니다.
Branch statements allow the program to execute certain parts of code depending on the value of one or more conditions. The values of the conditions specified in a branch statement control how the program branches and, therefore, what block of code is executed. Swift has three branch statements: an if statement, a guard statement, and a switch statement.
If - else 문
가장 기본적인 분기처리 방법입니다. 특정 조건이 참인지 확인한 다음 조건에 따라 코드를 실행합니다.
let age = 20
if age >= 19 {
print("you are an adult.")
} else {
print("you are a minor.")
}
여러 조건도 if - else 문으로 나타낼 수 있습니다.
let score = 70
if score >= 90 {
print("you get an A grade.")
} else if score >= 80 {
print("you get a B grade.")
} else {
print("you get a C grade.")
}
Guard 문
Guard는 하나 혹은 그 이상의 조건이 충족되지 않을 때, 코드 블록을 빠져나오기 위해 사용하는 구문입니다. 이를 조기 종료(Early Exit)라고 하며, 코드의 가독성을 높이고 깊은 중첩을 피할 때 사용합니다.
guard #condition# else {
#statement#
}
- Guard 문의 조건은 반드시 bool(Boolean) 형식이여야 합니다. 즉, 참 혹은 거짓으로 나뉘는 조건이여야 합니다.
- Else 절의 상태 값은 아래 항목과 같이 Guard 문을 벗어나는 조건이여야 합니다.
- return
- break
- continue
- throw
If와 Guard 문의 차이
- If 문은 조건이 true일 때 실행되는 코드를 작성합니다.
- Guard 문은 조건이 false일 때 처리 로직을 먼저 작성하므로 주요 로직을 한 눈에 파악할 수 있습니다.
# if 문 사용 예시
if age >= 19 {
print("You are an adult!")
} else {
print("You are a minor.")
}
# guard 문 사용 예시
guard age >= 19 else {
print("You are a minor.")
return
}
print("You are an adult!")
Switch 문
Switch 문은 하나의 값에 대해 여러 경우를 평가하고, 각 경우에 맞는 코드를 실행하는 방식입니다.
let fruit = "apple"
switch fruit {
case "Apple":
print("This is an apple.")
case "Banana":
print("This is a banana.")
default:
print("I don't know.")
}
print(fruit)
위 코드에서는 값이 "This is an apple." 로 값이 출력될 것입니다.
고급 분기 처리 (1) 튜플 분기
Switch 문은 튜플 형태로 여러 값을 동시에 평가할 수 있습니다.
튜플(Tuple)이란?
변경할 수 없는(immutable) 데이터 구조로 여러 개의 값을 하나로 묶어 저장할 수 있는 자료입니다. 리스트와 유사하지만, 한 번 생성되면 그 값을 변경할 수 없습니다. 튜플은 소괄호를 사용하여 정의하며, 다양한 데이터 타입을 혼합하여 저장할 수 있습니다.
let weather = (temperature: 15, condition: "Rainy")
switch weather {
case (..<0, _):
print("It's freezing outside.")
case (0...10, "Rainy"):
print("It's a cold and rainy.")
case (0...10, _):
print("It's a cold outside.")
case (11...25, "Sunny"):
print("It's a nice weather.")
case (26..., _):
print("It's hot weather.")
default:
print("Weather conditions are not recognized.")
}
print(weather)
위 코드에서는 "Weather conditions are not recognized."로 값이 출력될 것입니다.
고급 분기 처리 (2) 값 바인딩
Switch 문에서 조건을 만족하는 값을 변수에 바인딩하여 사용할 수 있습니다.
let value = 10
switch value {
case let x where x > 0:
print("Positive number: \(x)")
case let x where x < 0:
print("Negative number: \(x)")
default:
print("Zero")
}
print(value)
위 코드에서는 "Positive number: 10"으로 값이 출력될 것입니다.
고급 분기 처리 (3) 열거형과 switch
열거형(enum)은 상태를 나타내는 데 사용되며, switch와 함께 사용하면 각 상태에 대한 코드를 간결히 작성할 수 있습니다.
enum fruit {
case apple
case banana
case melon
case strawberry
}
let minchae = fruit.banana
switch minchae {
case apple:
print("she wants to eat an apple.")
case banana:
print("she wants to eat a banana.")
case melon:
print("she wants to eat a piece of melon.")
case strawberry:
print("she likes blueberry more but she also wants to eat a strawberry.")
}
print(minchae)
위 코드에서는 "she wants to eat a banana."가 출력될 것입니다.
반면, switch는 class가 instance(self)를 검사하는 데에도 사용합니다. 특히 열거형이나 여러 property를 평가할 때 유용합니다.
enum device {
case phone(model: String)
case laptop(brand: String)
case tablet
func deviceInfo() {
switch self { # 현재 인스턴스를 나타냄
case .phone(let model):
print("This is a phone. Model: \(model)")
case .laptop(let model):
print("This is a laptop. Brand: \(brand)")
case .tablet:
print("This is a tablet.")
}
}
}
let myDevice = device.phone(model: "iPhone 14")
myDevice.deviceInfo()
위 코드에서는 "This is a phone. Model: iPhone 14"라는 값이 출력될 것입니다.
'App Development > Swift' 카테고리의 다른 글
Swift의 매개변수(parameter) 정리하기 (0) | 2024.11.30 |
---|---|
Swift에서의 completion (0) | 2024.11.26 |
Swift의 Closure 란? (0) | 2024.11.25 |
Swift의 ARC (Automatic Reference Counting) (0) | 2024.11.24 |
Swift에서의 Class (0) | 2024.11.24 |