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

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
longlivedrgn

Miro 찾기

[Swift] Optional Binding(nil-coalescing)
Swift

[Swift] Optional Binding(nil-coalescing)

2023. 2. 11. 20:45

Nil-Coalescing Operator

→ Optional Type 표현식에 값이 저장되어 있는 지 확인하고 꺼낼 필요가 없어진다.

a ?? b 일 때, a는 옵셔널 값이고, 옵셔널에서 값을 추출하여 값이 있으면 a 옵셔널의 값을 반환하고, 값이 없으면 b 값을 반환한다.

  • 예를 통해서 알아보자. 아래와 같이 옵셔널 스트링을 선언해보자.
let name: String? = "Miro"
  • 옵셔널 바인딩을 통해서 print를 해보자.
if let name = name {
    print("Hello, \(name)")
} else {
    print("hello, what's your name")
}
// Hello, Miro

만약, nil-coalescing을 사용한다면? 아래와 같이 사용이 가능하다.

print("hello, "+ (name ?? "what's your name?"))

즉,

  • name에 값이 있을 경우 ⇒ name의 Unwrapping 된 값을 Return한다.
  • name에 값이 없을 경우(nil) ⇒ 오른쪽 피연산자 값을 Return 한다.

‼️ 단, ??를 사이로 같은 Type이여야한다.

Optional String Type ?? Non-Optional String Type → 가능

Optional String Type ?? Non-Optional Int Type → 불가능

 

추가적인 nil-coalescing operator의 예)

→ Dictionary에서 key값을 통해 value 값을 뽑아낼 때 optional binding을 해야되는데, 만약 nil이라면 0을 nil이 아니라면 해당 값을 뽑아낸다!

fruitStore.stock[fruit] ?? 0
 
저작자표시

'Swift' 카테고리의 다른 글

[Swift] 상속(Inheritance)  (0) 2023.02.11
[Swift] Lazy (지연 저장 프로퍼티)  (0) 2023.02.11
[Swift] 고차함수(Map,Filter,Reduce), allSatisfy, forEach,enumerated()  (0) 2023.02.11
[Swift] guard VS if  (0) 2023.02.04
[Swift] , 와 &&의 차이점  (0) 2023.02.04
    'Swift' 카테고리의 다른 글
    • [Swift] 상속(Inheritance)
    • [Swift] Lazy (지연 저장 프로퍼티)
    • [Swift] 고차함수(Map,Filter,Reduce), allSatisfy, forEach,enumerated()
    • [Swift] guard VS if
    longlivedrgn
    longlivedrgn

    티스토리툴바