3.4 Guard


Guard

  • ifゲートとは逆に、条件はfalse時運転のコード
  • guard condition else {
      // false: execute some code
    }
     
    // true: execute some code 
  • 上端else通過ifまず条件に合わない状態をフィルタリングし、設計関数に下端をコアコードにするのに役立ちます.
  • func divide(_ number: Double, by divisor: Double) {
    
      // 나누는 수가 0인 경우를 먼저 걸러낸다.
      guard divisor != 0.0 else {
        return
      }
      
      // 핵심 로직
      let result = number / divisor
      print(result)
    }

    guard vs if

  • guardドアで似たようなデザインができます.
  • func divide(_ number: Double, by divisor: Double) {
      if divisor == 0.0 { return }
      let result = number / divisor
      print(result)
    }
  • ただし、関数条件が明確なのはif
  • // 나누는 수가 0이 되면 안된다는 것을 명확하게 보여줌
    guard divisor != 0.0 else { return }
    関数の条件を理解し、内部コードを一目で見ると便利です.
    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と同様に、オプションから値を抽出できます.

  • 抽出値がnilの場合、elseゲートを実行します.
  • if-letと異なり、外部から接近し続けることが可能
  • // 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と同様に、複数のオプション値を一度に抽出することができる.
  • // 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.)
    }