[TIL] guard let

술술·2024년 3월 20일

TIL

목록 보기
10/21

guard let

  • if let 구문과 다르게 else를 생략할 수 없다.
  • guard 뒤 따라오는 Bool 값이 false라면 else의 블록 내부 코드를 실행
  • else에 return, break, Throw, continue 등의 '제어문 전환 명령어'를 반드시 넣어야 사용 가능하다.
  • else 내부 코드는 자신보다 상위 코드 블록을 종료하는 코드가 반드시 들어가야 한다.
  • 예외처리를 할 경우 guard let 을 사용하는 것이 if let보다 더욱 깔끔하고 명료하게 사용할 수 있다.
  • 전역변수(함수 내부의 지역상수)로 사용이 가능하다.
    @objc func switchValueChanged(_ sender: UISwitch) {
      guard let cell = sender.superview as? UITableViewCell, else { return }
      let indexPath = tableView.indexPath(for: cell)
      toDo[indexPath.row].isComplete = sender.isOn
    }
profile
Hello

0개의 댓글