소피it블로그

[Swift 공식문서] Control Flow - Early Exit 정리 (guard문) 본문

개발_iOS/스위프트

[Swift 공식문서] Control Flow - Early Exit 정리 (guard문)

sophie_l 2022. 8. 21. 14:49

https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html

 

Control Flow — The Swift Programming Language (Swift 5.7)

Control Flow Swift provides a variety of control flow statements. These include while loops to perform a task multiple times; if, guard, and switch statements to execute different branches of code based on certain conditions; and statements such as break a

docs.swift.org

guard문은 if문과 마찬가지로 표현의 불리언 값에 따라 구문을 실행한다. guard문을 사용할 때는 조건이 반드시 참이어야만 guard 표현 뒤의 코드가 실행된다. if문과 달리 guard문은 항상 else 절을 갖는다. else문 내의 코드는 조건이 참이 아닐 때 실행된다.

func greet(person: [String: String]) {
    guard let name = person["name"] else {
        return
    }

    print("Hello \(name)!")

    guard let location = person["location"] else {
        print("I hope the weather is nice near you.")
        return
    }

    print("I hope the weather is nice in \(location).")
}

greet(person: ["name": "John"])
// Prints "Hello John!"
// Prints "I hope the weather is nice near you."
greet(person: ["name": "Jane", "location": "Cupertino"])
// Prints "Hello Jane!"
// Prints "I hope the weather is nice in Cupertino."

guard문의 조건이 만족되면 guard문을 닫는 중괄호 뒤의 코드가 실행된다. 옵셔널 바인딩에서 조건의 일부로서 값을 할당받은 변수나 상수는 guard문이 나타나는 코드 블록 안에서 사용이 가능하다.

조건이 충족되지 않을 경우에는 else문 내의 코드가 실행된다. else문은 guard문이 나타나는 코드 블록을 벗어날 수 있도록 제어를 옮겨야 한다. return, continue, throw 등의 제어 변경문을 사용하거나, fatalError(_:file:line:) 등의 return 없는 함수 또는 메서드를 호출하면 된다.

guard문을 사용하면 if문을 사용할 때에 비해 코드의 가독성이 향상된다. 이를 통해 else구문으로 감쌀 필요 없이 실행되는 코드를 작성할 수 있으며, 위배된 요구사항을 처리할 코드를 해당 요구사항 옆에 적어줄 수 있다.