๐ŸŽ iOS/Swift

[Swift] Guard๋ฌธ | guard let

Guard๋ฌธ์€ ๋ฐ˜๋“œ์‹œ ์žˆ์–ด์•ผ ํ•  ์กฐ๊ฑด์„ ๊ฒ€์‚ฌํ•˜์—ฌ ๊ทธ ๋‹ค์Œ์— ์˜ค๋Š” ์ฝ”๋“œ๋“ค์„ ์‹คํ–‰ํ• ์ง€ ๋ง์ง€ ๊ฒฐ์ •ํ•œ๋‹ค.

Guard๋ฅผ ์ด์šฉํ•˜๋Š” ์ด์œ ๋ฅผ ์ •๋ฆฌํ•˜์ž๋ฉด ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

 

1. control flow์™€ indentation์„ ๋‹จ์ˆœํ•˜๊ฒŒ ํ•˜๊ธฐ์œ„ํ•ด

    → ์ฝ”๋“œ๊ฐ€ ๊น”๋”ํ•ด์ง€๊ณ  ๊ทธ๋กœ ์ธํ•ด ์—๋Ÿฌ๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค.

2. ๋ถ€์ ์ ˆํ•œ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋น ๋ฅด๊ฒŒ ์—†์• ๋ฒ„๋ฆฌ๊ธฐ ์œ„ํ•ด

 

if๋ฌธ vs guard๋ฌธ

 

if๋ฌธ ์‚ฌ์šฉ ver.

func singHappyBirthday(){
    if(birthdayIsToday){
        if(invitedGuests > 0){
            if (cakeCandleLit){
                print("Happy Birthday to you!")
            }else{
                print("์ผ€์ต ์ด›๋ถˆ ๋ถˆ ์•ˆ์ผœ์ง")
            }
        }else{
            print("์ดˆ๋Œ€ ์•„๋ฌด๋„ ์•ˆํ•จ")
        }
    }else{
        print("์˜ค๋Š˜์€ ์•„๋ฌด๋„ ์ƒ์ผ ์•„๋‹˜")
        return
    }
}

 

Guard ์‚ฌ์šฉ ver.

- else์ผ ๋•Œ ๋‚ด๋ถ€๊ฐ€ ์‹คํ–‰๋˜์–ด์„œ ๋ฆฌํ„ด์„ ํ•ด์„œ ํ•จ์ˆ˜๋ฅผ ๋๋ƒ„

func singHappyBirthday(){
    guard birthdayIsToday else{
        print("์˜ค๋Š˜์€ ์•„๋ฌด๋„ ์ƒ์ผ์ด ์•„๋‹˜")
        return
    }
    
    guard invitedGuests > 0 else{
        print("์ดˆ๋Œ€ ์•„๋ฌด๋„ ์•ˆํ•จ")
        return
    }
    
    guard cakeCandleLit else {
        print("์ผ€์ต ์ด›๋ถˆ ๋ถˆ ์•ˆ์ผœ์ง")
        return
    }
    
    print("Happy Birthday to you")
}

 

 

Guard with Optionals - guard let

 

if let ์‚ฌ์šฉ ver.

- unwrap๋œ ์ƒ์ˆ˜๋Š” if let ๊ตฌ๋ฌธ ์•ˆ์—์„œ๋งŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

func processBook(title: String?, price: Double?, pages: Int?){
    if let theTitle = title, let thePrice = price, let thePages = pages{
        print("\(theTitle) costs $\(thePrice) and has \(thePages)pages.")
    }
}

 

guard let ์‚ฌ์šฉ ver.

- unwrap๋œ ์ƒ์ˆ˜๋ฅผ ์ผ๋ฐ˜ ์ƒ์ˆ˜์ฒ˜๋Ÿผ ๊ทธ ํ•จ์ˆ˜ ๋๊นŒ์ง€ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

func processBook(title: String?, price: Double?, pages: Int?){
    guard let theTitle = title, let thePrice = price, let thePages = pages else {return}
        print("\(theTitle) costs $\(thePrice) and has \(thePages)pages.")
}