Search
Duplicate

빠른 종료(early exit) (guard)

생성일
2023/08/06 14:50
태그
Grammar

빠른 종료 (guard)

빠른 종료의 핵심 키워드는 guard 이다.
guard 구문은 if 구문과 유사하게 Bool 타입의 값으로 동작하는 기능이다.
guard 뒤에 따라붙는 코드의 실행 결과가 true 일 때 코드가 계속 실행 된다.
if 문과는 다르게 guard 구문은 항상 else 구문이 뒤에 따라와야 한다.
만약 guard 뒤에 따라오는 Bool 값이 false라면 else의 블록 내부 코드를 실행하게 되는데, 이때 else 구문의 블록 내부에는 꼭 자신보다 상위의 코드 블록을 종료하는 코드가 들어가게 된다.
그래서 특정 조건에 부합하지 않다는 판단이 되면 재빠르게 코드 블록의 실행을 종료할 수 있다.
코드 블록을 종료할 때는 return, break, continue, throw 등의 제어문 전환 명령을 사용한다.
guard Bool 타입값 else { 예외사항 실행문 제어문 전환 명령어 }
Swift
복사
guard 구문을 사용하면 if 코드를 훨씬 간결하고 읽기 좋게 구성할 수 있다. if 구문을 사용하면 예외사항을 else 블록으로 처리해야 하지만 예외사항만을 처리하고 싶다면 guard 구문을 사용하는 것이 훨씬 간편하다.
// if 구문 for i in 0...3 { if i == 2 { print(i) } else { continue } } // guard 구문 for i in 0...3 { guard i == 2 else { continue } print(i) }
Swift
복사

Bool 타입의 값으로 guard구문의 옵셔널 바인딩의 역할

func greet(_ person: [String: String]) { guard let name: String = person["name"] else { return } print("Hello \(name)!") guard let location: String = person["location"] else { print("I hope the weather is nice near you") return } print("I hope the weather is nice in \(location)") } var personInfo: [String: String] = [String: String]() personInfo["name"] = "Jenny" greet(personInfo) // Hello Jenny! // I hope the weather is nice near you personInfo["location"] = "Korea" greet(personInfo) // Hello Jenny! // I hope the weather is nice in Korea
Swift
복사
조금 더 발전
func fullAddress() -> String? { var restAddress: String? = nil if let buildingInfo: Building = self.building { restAddress = buildingInfo.name } else if let detail = self.detailAddress { restAddress = detail } if let rest: String = restAddress { var fullAddress: String = self.province fullAddress += " " + self.city fullAddress += " " + self.street fullAddress += " " + rest return fullAddress } else { return nil } } // 서로 비교 func fullAddress() -> String? { var restAddress: String? = nil if let buildingInfo: Building = self.building { restAddress = buildingInfo.name } else if let detail = self.detailAddress { restAddress = detail } guard let rest: String = restAddress else { return nil } var fullAddress: String = self.province fullAddress += " " + self.city fullAddress += " " + self.street fullAddress += " " + rest return fullAddress }
Swift
복사
조금 더 구체적인 조건을 추가하고 싶다면 쉽표(,)로 추가조건을 나열해주면 된다.
추가된 조건은 Bool 타입 값이어야 한다. 또, 쉼표로 추가된 조건은 AND 논리연산과 같은 결과를 낸다.
즉, 쉽표를 &&로 치환해도 같은 결과를 얻을 수 있다는 뜻이다.
guard 구문에 구체적인 조건을 추가
func enterClub(name: String?, age: Int?) { guard let name: String = name, let age: Int = age, age > 19, name.isEmpty == false else { print("You are too young to enter the club") return } print("Welcome \(name)!") }
Swift
복사
guard 구문의 한계는 자신을 감싸는 코드 블록, 즉 return, break, continue, throw 등의 제어문 전환 명령어를 쓸 수 없는 상황이라면 사용이 불가능하다는 점입니다. 함수나 메서드, 반복문 등 특정 블록 내부에 위치하지 않는다면 사용이 제한된다.
let first: Int = 3 let second: Int = 5 guard first > second else { // 오류 }
Swift
복사