longlivedrgn
Miro 찾기
longlivedrgn
전체 방문자
오늘
어제
  • 분류 전체보기 (74)
    • Swift (36)
    • iOS (31)
    • Algorithm (0)
    • Architecture, Design Patter.. (1)
    • Computer Science (6)
      • 컴퓨터 네트워크 (6)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
longlivedrgn

Miro 찾기

[Swift] guard VS if
Swift

[Swift] guard VS if

2023. 2. 4. 16:24

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에서 if 와 guard중에 뭘 써야하나...

[Swift] if let vs guard let (응용편)

저작자표시 (새창열림)

'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
    'Swift' 카테고리의 다른 글
    • [Swift] Optional Binding(nil-coalescing)
    • [Swift] 고차함수(Map,Filter,Reduce), allSatisfy, forEach,enumerated()
    • [Swift] , 와 &&의 차이점
    • [Swift] - Access Control
    longlivedrgn
    longlivedrgn

    티스토리툴바