3.4 Guard

Joohyun·2022년 4월 14일
0

Guard

  • if문과 반대로 조건이 false일 때 실행되는 코드
guard condition else {
  // false: execute some code
}
 
// true: execute some code 
  • 상단에서 else를 통해 조건이 맞지 않는 상태를 먼저 걸러내고, 하단에 핵심 코드가 진행되도록 함수를 디자인하는데 유용하다.
func divide(_ number: Double, by divisor: Double) {

  // 나누는 수가 0인 경우를 먼저 걸러낸다.
  guard divisor != 0.0 else {
    return
  }
  
  // 핵심 로직
  let result = number / divisor
  print(result)
}

if vs guard

  • if문을 사용해 비슷한 디자인을 구현할 수 있다.
func divide(_ number: Double, by divisor: Double) {
  if divisor == 0.0 { return }
  let result = number / divisor
  print(result)
}
  • 하지만, 함수의 조건을 명확하게 보여주는 것은 guard이다.
// 나누는 수가 0이 되면 안된다는 것을 명확하게 보여줌
guard divisor != 0.0 else { return }
  • if문을 사용하는 것(pyramid of doom)보다 함수의 조건을 파악하고 내부 코드를 한눈에 보기 유용하다.
func singHappyBirthday() {
  guard birthdayIsToday else {
    print(No one has a birthday today.)
    return
  }
 
  guard !invitedGuests.isEmpty else {
    print(It’s just a family party.)
    return
  }
 
  guard cakeCandlesLit else {
    print(The cake’s candles haven’t been lit.)
    return
  }
 
  print(Happy Birthday to you!)
}

pyramid of doom

  • if문 내부에 if문이 계속 반복되는 코드
func singHappyBirthday() {
  if birthdayIsToday {
      if !invitedGuests.isEmpty {
          if cakeCandlesLit {
              print(Happy Birthday to you!)
          } else {
              print(The cake’s candles haven’t been lit.)
          }
      } else {
          print(It’s just a family party.)
    }
  } else {
      print(No one has a birthday today.)
  }
}

Guard with Optionals (guard let)

  • if-let과 유사하게 optional에서 값 추출이 가능하다.

  • 추출할 값이 nil일 경우에는 else문이 실행된다.

  • if-let과 달리, 외부에서 해당 constant로의 접근이 가능하다.

// if-let
if let eggs = goose.eggs {
  print(The goose laid \(eggs.count) eggs.)
}

// 이곳에선 `eggs`에 접근할 수 없음
// guard let
guard let eggs = goose.eggs else { return }

// `eggs`에 접근 가능 
print(The goose laid \(eggs.count) eggs.)
  • if let과 동일하게 한번에 여러개의 optional의 값을 추출할 수 있다.
// 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
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.)
}
profile
IOS Developer

0개의 댓글