Swift: Nil Coalescing Operation / ?? 연산자

Wooyo·2023년 10월 24일
0
post-thumbnail

참고 사이트 : https://babbab2.tistory.com/20

1. Nil Coalescing Operator / ?? 연산자

  • optional type의 표현식 값이 저장되어 있는지 확인 후 사용하기 위한 연산자
  • 아래와 같이 표현
Optional Expression ?? Non-Optional Expression
// 옵셔널이 nil이 아닐 경우 반환값 ?? 옵셔널이 nil일 경우 반환값

2. 사용예

  • 다음과 같은 optional type의 상수가 존재하는 경우를 상정
let name: String? = "Jimin"
  • name != nil : hello Jimin
  • name == nil : hello, what is your name?
  • 위와 같이 출력을 하고 싶은 경우 기존의 if let 방식을 이용한다면 아래와 같다
if let name = name {
	print("hello \(name)")
} else {
	print("hello, what is your name?")
}
  • ?? 연산자를 사용한다면 다음과 같다
print("hello " + (name ?? "what is your name?"))

3. 주의점

  • ?? 연산자에 사용되는 옵셔널일 경우의 반환값과 옵셔널이 아닐 경우의 반환값은 같아야함
profile
Wooyo의 개발 블로그

0개의 댓글