https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html
출처는 위 swift 공식문서의 Control Flow에서 Early Exit 부분이다. 아래의 설명과 예시는 모두 위 주소에서 가져온 것이다.
guard는 if문에서 else 부분에 해당한다. if문은 조건이 참이면 if 부분이, 거짓이면 else 부분이 실행되는데 guard는 그 반대라고 볼 수 있다. guard 조건이 거짓이면 guard문의 else {...} 부분이 실행되고 참이면 else {...} 다음으로 나오는 부분이 실행된다.
공식문서에서 나오기를 if {...} else {...} 보다 guard를 사용하는 것이 더 읽기 편하다고 한다. (가독성 좋음)
자바스크립트 할때도 if ... else는 최대한 지양하고 가능하면 삼항연산자로 처리하곤 했는데 swift에는 guard가 있었다.
아직 guard를 쓸 상황(?)은 없었는데 guard문이 '필터' 같은 느낌이다. nil이나 false인 조건들을 guard에서 걸러주고 true 혹은 valid 조건들을 guard 바깥에서 처리하면 되니까.
아무튼 swift 공식문서에서 나온 guard 문 예시는 아래와 같다.
// guard문 사용 (출처: https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html)
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)!") // guard 문의 변수를 guard {...} 바깥에서도 사용할 수 있음
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"])
이제 이것을 if문으로 작성해보면,
func greet(person: [String: String]) {
if let name = person["name"] {
print("Hello \(name)!!")
} else {
return
}
if let location = person["location"] {
print("I hope the weather is nice in \(location).")
return
}
print("I hope the weather is nice near you.")
/*
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"])
대충 이렇게 될 것 같다.
guard문을 사용하면 guard 바깥 부분이 참일때 실행되는 부분이라는 것이 깔끔하게 보이는데 if ... else 를 사용해버리면 참일 때는 어떻고 else로 넘어가면 어떻고.. 이걸 하나하나 읽어야 하니, 코드 흐름이 눈에 빨리 들어오지 않는 단점이 있는 것 같다.
'swift & iOS > swift' 카테고리의 다른 글
[swift] 함수에 함수를 전달하거나 함수를 리턴하거나 (0) | 2022.01.16 |
---|---|
[swift] 함수에 여러 개의 argument 넣기(...) (0) | 2022.01.16 |
[swift] switch문 case에 조건 달기 (where 키워드) (0) | 2022.01.16 |
[Swift] 정수 나누기 (9 나누기 10을 했는데 0이 나오다) (0) | 2022.01.14 |
[swift] 연산자들 (==, ..., ??) (0) | 2022.01.10 |