티스토리 뷰

Apple/Swift

[Swift 5.9] if and switch expressions

doyeonjeong_ 2024. 1. 8. 22:52

원문 : https://www.hackingwithswift.com/swift/5.9/if-switch-expressions

기능

if 와 switch를 표현식으로 사용할 수 있게 되었다.

// if 문 예시
let score = 800
let simpleResult = if score > 500 { "Pass" } else { "Fail" }
print(simpleResult)
// switch 문 예시
let complexResult = switch score {
    case 0...300: "Fail"
    case 301...500: "Pass"
    case 501...800: "Merit"
    default: "Distinction"
}

print(complexResult)

이를 함수에 응용하면 아래와 같이 쓸 수 있다.

func rating(for score: Int) -> String {
    switch score {
    case 0...300: "Fail"
    case 301...500: "Pass"
    case 501...800: "Merit"
    default: "Distinction"
    }
}

print(rating(for: score))

삼항식도 쌉가능

let ternaryResult = score > 500 ? "Pass" : "Fail"
print(ternaryResult)

주의

let customerRating = 4
let bonusMultiplier1 = customerRating > 3 ? 1.5 : 1
let bonusMultiplier2 = if customerRating > 3 { 1.5 } else { 1.0 }

삼항식에서는 1.5 : 1 이라고 쓸 경우 자동으로 1을 1.0으로 인식하지만 업데이트 된 if문 에서는 1.0 으로 적어줘야 한다.

왜냐하면 삼항식은 한번에 2가지 결과를 검사하지만, if 문은 각각의 결과값을 반환할 때 검사하므로 Double 과 Int라는 독립적인 값을 반환하게 되기 때문이다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/06   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
글 보관함