if 연산자는 조건이 true 또는 false 여부를 결정하기 위해 논리 또는 비교 연산자를 결합하여 사용한다.== : 2개의 값이 서로 동일해야 true
!= : 2개의 값이 서로 동일하지 않아야 true
> : 왼쪽 값이 오른쪽 값보다 커야 true
>= : 왼쪽 값이 오른쪽 값보다 크거나 같아야 true
< : 왼쪽 값이 오른쪽 값보다 작아야 true
<= : 왼쪽 값이 오른쪽 값보다 작거나 같아야 true
&& : AND, 2개의 상태가 모두 true여야만 true
|| : OR, 2개의 상태 중 1개 이상이 true여야만 true
! : NOT, 값의 반대 상태를 반환
if 조건이 true 이면 코드 블럭을 실행하고, false 이면 실행하지 않고 넘어간다.let temperature = 100
if temperature >= 100 { // true 이므로 "물이 끓는 중"이 출력된다.
print(”물이 끓는 중”)
}
if 조건이 false 인 경우 실행할 코드 블럭을 else 문을 통해 지정할 수 있다.let temperature = 100
if temperature >= 100 { // true
print(”물이 끓는 중”)
} else {
print(”물이 끓지 않음”)
}
else if 문을 추가해 조건을 여러개 만들 수 있다.var finishPosition = 2
if finishPosition == 1 {
print(”금메달”)
} else if finishPosition == 2 { // true
print(”은메달”)
} else {
print(”동메달 또는 메달 획득 실패”)
}
Bool 타입은 true 또는 false 값만 가능하다.
비교 연산자를 통해 Bool 값을 할당해줄 수 있다.
let number = 1000
let isSmallNumber = number < 10 // false
! 논리 연산자를 통해 Bool 값을 변경할 수 있다.var isSnowing = false
if !isSnowing { // true
print("눈이 오지 않음")
}
&& 논리 연산자를 통해 조건들이 모두 true 인지 체크할 수 있다.let temperature = 70
if temperature >= 65 && temperature <= 75 { // true
print("적절한 온도")
} else if temperature < 65 {
print("낮은 온도")
} else {
print("높은 온도")
}
|| 논리 연산자를 통해 조건들 중 적어도 1개가 true인지 체크할 수 있다.var isPluggedIn = false
var hasBatteryPower = true
if isPluggedIn || hasBatteryPower { // true
print(”사용 가능”)
} else {
print(”😱”)
}
하나의 값에 대한 조건이 너무 많아지는 경우 if ... else 를 여러개 나열하는 대신 간결한 switch 문을 사용한다.
case에 따라 실행할 코드블럭을 나눌 수 있고, 어느 케이스에도 포함되지 않는 경우 default문이 실행된다.
let numberOfWheels = 2
switch numberOfWheels {
case 0: // numberOfWheels == 0
print("Missing something?")
case 1: // numberOfWheels == 1
print(”Unicycle”)
case 2: // numberOfWheels == 2
print(”Bicycle”)
case 3: // numberOfWheels == 3
print(”Tricycle”)
case 4: // numberOfWheels == 4
print(”Quadcycle”)
default: // // numberOfWheels > 4
print(”That’s a lot of wheels!”)
}
case 문 하나에 여러 조건이 올 수 있다.let character = “z”
switch character {
case “a”, “e”, “i”, “o”, “u”: // character가 모음이라면 실행
print(”This character is a vowel.”)
default: // character가 자음이라면 실행
print(”This character is a consonant.”)
}
case 문 내부에 값의 범위를 지정할 수 있다.switch distance {
case 0...9: // 0 <= d <= 9
print(”close”)
case 10...99: // 10 <= d <= 99
print(”medium distance”)
case 100...999: // 100 <= d <= 999
print(”far”)
default: // d > 1000
print(”so far”)
}
?:문을 통해 간결하게 표현할 수 있다.var largest: Int
let a = 15
let b = 4
// if문 사용 시
if a > b {
largest = a
} else {
largest = b
}
// ?:문 사용시
largest = a > b ? a : b
- max 함수를 통해 더 간단하게 표현할 수도 있다
largest = max(a, b)