guard
- guard문 속 else문에서는 return(or break, continue, throw)으로 즉시 종료시킨다.
gurad 조건 else{
//조건이 false면 실행된다.
return
}
guard문을 사용하는 이유?
→ 가독성이 훨씬 좋아진다.
if문일 경우
func solution() {
if condition1 {
if condition2 {
if condition 3 {
print("come in")
} else {
print("bye")
}
} else {
print("bye")
}
} else {
print("bye")
}
}
// 세 조건이 모두 참이면 come in, 하나라도 거짓이면 bye를 출력하는 함수이다.
guard문일 경우
func solution() {
guard condition1 else { return print("bye") }
guard [condition2](https://www.notion.so/22-12-27-84b65c1909c64641808722a79c483b01) else { return print("bye") }
guard condition3 else { return print("bye") }
print("come in")
}
if let VS guard let
- if let
→ str은 지역변수이므로 if block 밖에서 사용하면 에러가 난다!
if let str = data {
print("data :: \(str)")
} else {
print("data is nil")
}
print(str) // 에러!!
- guard let
→ str은 전역변수이므로 guard block 밖에서 사용해도 에러가 나지 않는다.
guard let str = data {
return
}
print(str) // 에러가 생기지 않는다!
'Swift' 카테고리의 다른 글
[Swift] Optional Binding(nil-coalescing) (0) | 2023.02.11 |
---|---|
[Swift] 고차함수(Map,Filter,Reduce), allSatisfy, forEach,enumerated() (0) | 2023.02.11 |
[Swift] , 와 &&의 차이점 (0) | 2023.02.04 |
[Swift] - Access Control (0) | 2023.02.04 |
[Swift] 연산 프로퍼티 (0) | 2023.02.04 |