콘텐츠로 건너뛰기

[야곰 Swift 프로그래밍] 14 옵셔널 체이닝과 빠른 종료

14.1 옵셔널 체이닝 (Optional Chaining)

14.2 빠른 종료 (Early Exit)

  • 빠른 종료의 핵심 키워드는 guard
  • guard 구문은 if 구문과 유사하게 Bool 타입의 값으로 동작하는 기능
  • guard 뒤에 따라붙는 코드의 실행 결과가 true일 때 코드가 계속 실행 됨
  • guard 뒤에 따라오는 Bool 값이 false라면 else의 블록 내부 코드를 실행하게 되는데, 이때 else 구문의 블록 내부에는 꼭 자신보다 상위의 코드 블록을 종료하는 코드가 들어가게 됨. 그래서 특정 조건에 부합하지 않다는 판단이 되면 재빠르게 코드 블록의 실행을 종료 할 수 있음
  • 코드 블록 종료 시 return, break, continue, throw 등의 제어문 전환 명령을 사용

guard 문 기본 형태

 guard Bool 타입 값 else {
    예외사항 실행문
    제어문 전환 명령어
 }
// 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]() // 딕셔너리. 키가 String, 값이 String 타입인 빈 딕셔너리 생성
// var personInfo: Dictionary<String, String> = Dictionary<String,String> 과 같은 표현

personInfo["name"] = "Jenny"
greet(personInfo) // I hope the weather is nice near you

personInfo["location"] = "Korea"

greet(personInfo)
// Hello Jenny!
// I hope the weather is nice in Korea
// 조금 더 구체적인 조건을 추가하고 싶다면 쉼표로 추가조건을 나열해주면 됨. 추가된 조건은 Bool 타입 값이어야 함
// 쉼로 추가된 조건은 AND 논리연산과 같은 결과를 줌. 즉, 쉼표를 &&로 치환해도 같은 결과를 얻을 수 있음
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)!")
}

enterClub(name: "Jinny", age: 18)

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다