1. guard 구문
- guard 문은 else 블록에서 코드의 실행을 종료해야 하고 else블록은 생략이 불가합니다.
- guard 문의 condition은 true 또는 false가 리턴되어야 합니다.
- condition이 true면 실행되는 블록은 없습니다.
- condition이 false일 경우 else 블록이 실행됩니다.
- optionalBinding과 사용할 수 있습니다.
- return, throw를 호출해서 스코프를 탈출해야 합니다.
- guard문은 코드의 중첩을 피할 수 있고 코드가 깔끔해지는 장점이 있습니다.
guard condition else {
statements
}
guard condition else {
statement
}
func divide(base: Int) {
guard base != 0 else {
print("연산 불가")
return
}
let result = 100 / base
print(result)
}
divide(base: 10)
func check(id: String?) -> Bool {
guard let id = id else {
return false
}
guard id.count >= 5 else {
return false
}
return true
}
check(id: "guardID")