Swift Control Flow - if, switch

유진혁·2023년 12월 5일
0

swift

목록 보기
17/17

If

if의 조건이 true이면 해당하는 statements를 실행한다.

var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
}
// "It's very cold. Consider wearing a scarf." 출력

else를 사용하여 해당하는 조건이 false일 경우 실행할 statements를 지정할 수 있다.

temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else {
    print("It's not that cold. Wear a T-shirt.")
}
// "It's not that cold. Wear a T-shirt." 출력

else if를 사용하여 여러개의 조건을 비교하여 실행 할 수 있다.

temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
} else {
    print("It's not that cold. Wear a T-shirt.")
}
// "It's really warm. Don't forget to wear sunscreen." 출력

아래의 예제 처럼 마지막 else는 생략이 가능하다.

temperatureInFahrenheit = 72
if temperatureInFahrenheit <= 32 {
    print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
    print("It's really warm. Don't forget to wear sunscreen.")
}

Swift는 변수에 값을 할당할 때 단축 표현을 지원한다.

아래와 같은 코드를

let temperatureInCelsius = 25
let weatherAdvice: String


if temperatureInCelsius <= 0 {
    weatherAdvice = "It's very cold. Consider wearing a scarf."
} else if temperatureInCelsius >= 30 {
    weatherAdvice = "It's really warm. Don't forget to wear sunscreen."
} else {
    weatherAdvice = "It's not that cold. Wear a T-shirt."
}


print(weatherAdvice)
// "It's not that cold. Wear a T-shirt." 출력

이처럼 단축표현을 사용할 수 있다.

let weatherAdvice = if temperatureInCelsius <= 0 {
    "It's very cold. Consider wearing a scarf."
} else if temperatureInCelsius >= 30 {
    "It's really warm. Don't forget to wear sunscreen."
} else {
    "It's not that cold. Wear a T-shirt."
}


print(weatherAdvice)
// "It's not that cold. Wear a T-shirt." 출력

Switch

switch statement는 값을 비교하여 같은 값일 때의 statement를 실행한다.

기본적인 사용법은 다음과 같다.

switch <#some value to consider#> {
case <#value 1#>:
    <#respond to value 1#>
case <#value 2#>,
    <#value 3#>:
    <#respond to value 2 or 3#>
default:
    <#otherwise, do something else#>
}

if statements 처럼 switch도 단축표현을 지원한다.

let anotherCharacter: Character = "a"
let message = switch anotherCharacter {
case "a":
    "The first letter of the Latin alphabet"
case "z":
    "The last letter of the Latin alphabet"
default:
    "Some other character"
}


print(message)
// "The first letter of the Latin alphabet" 출력

No Implicit Fallthrough

c나 object-c의 switch statements와 다르게 Swift의 switch는 break 없이도 아래로 이어지지 않는다.

Tuples

튜플을 사용해 여러개의 값을 같은 switch statement에서 비교하게 할 수 있다.

_를 모든 값에 해당하는 wildmask로 사용할 수 있다.

아래의 예제는 (x, y) 좌표를 받아 해당하는 statements를 실행한다.

let somePoint = (1, 1)
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, 1) is inside the box" 출력

위의 예제에서 (0, 0) 값은 4개의 케이스에 모두 해당하지만, 상기한 바와 같이 Swift의 switch는 처음 해당하는 case만을 실행한다.

Value Bindings

switch 문을 사용해 아래의 예제와 같이 변수에 값을 해당할 수 있다.

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" 출력

Where

switch문에서 where을 사용하여 추가적인 조건을 체크할 수 있다.

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" 출력

Compound Cases

여러개의 case를 한번에 비교할 수도 있다.

let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    print("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
    "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    print("\(someCharacter) is a consonant")
default:
    print("\(someCharacter) isn't a vowel or a consonant")
}
//  "e is a vowel" 출력 

위의 예제에서 "e"는 처음 case인 5개의 문자중 하나의 속하므로 "e is a vowel"이 출력된다.

또한 value bindings도 지원한다.

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" 출력

위의 예제에서 첫번째 케이스인 (let distance, 0), (0, let distance)는 y좌표가 0이거나 x좌표가 0일 때에 해당한다.

profile
개발자

0개의 댓글