1. 조건문 (Conditions)
- if 를 이용해서 조건에 따라 다른 프로그램이 실행 될수록 할수 있음
if 조건1 {
실행할 것
} else if 조건2 {
실행할 것
} else {
실행할 것
}
2. 조건 합치기 (Combining Conditions)
조건1과 조건2를 모두 충족할 때 -> if 조건1 && 조건2
조건1 또는 조건2를 충족할 때 -> if 조건1 || 조건2
3. 삼항 연산자 (Ternary Operator)
삼항 연산자를 이용해서 조건을 확인하고 true / false에 따른 값 할당이 가능하다.
let 변수명 = 조건 ? 참일 때 값 : 거짓일 때 값
// 예시
let text = age3 == age4 ? "same" : "not same"
>> 이전 문서: https://yurim-dev.tistory.com/13
[Swift] if...else 구문 대신 사용 가능한 Ternary Conditional Operator
Ternary operator는 구문 대신 사용될 수 있는 연산자이다. 3개의 피연산자를 취하므로 3항 연산자(Ternary Conditional Operator)라고 부른다. 문법 condition ? expression1 : expression2 의미: if condition is true, expression
yurim-dev.tistory.com
4. Switch 문 (Switch statement )
if - else 외에도 switch를 이용해서 조건을 확인할 수 있다.
단, 조건의 모든 케이스가 커버되게끔 작성해야 한다.
enum 타입과 같이 쓰기 좋다.
enum Direction {
case up
case down
case left
case right
}
let direction = Direction.down
switch direction {
case .up:
print("up")
case .down:
print("down")
case .left:
print("left")
case .right:
print("right")
}
'Swift > 문법' 카테고리의 다른 글
[Swift|문법] index 찾기 메소드 - enumerated(), firstIndex(of:), firstIndex(where:), lastIndex(of:), lastIndex(where) (0) | 2024.02.18 |
---|---|
[Swift|문법] vector (0) | 2024.02.18 |
[Swift] 연산자 (operator) - arithmetic, overloading, compound, comparison (0) | 2024.02.16 |
[Swift] 옵셔널(Optional) 제거 방법 3가지 (0) | 2024.02.15 |
[Swift] 고차함수 - map 시리즈(map, flatMap, compactMap) (0) | 2024.02.14 |