본문 바로가기
 IOS,Swift/Swift⌘

Swift - Optional Chaining

by 시에라177 2022. 7. 2.

옵셔널 체이닝

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.

-> 옵셔널 체이닝은 옵셔널 상태인 프로퍼티와 메서드 그리고 서브스크립트에게 nil인지 질의하고 답을 받는 과정. 옵셔널이 값을 가지고 있다면 성공적으로 응답할 것이지만, 만약 nil이라면 nil을 반환함. 여러개의 쿼리(질의)를 연결(체인)할 수 있다. 만약 어떤 체인이라도 닐이면 그 전체 체인은 nil을 반환할 것.....

--> 쉽게 말해 연속된 옵셔널을 연속하여 확인하는 것.

 

# 0.Optional Chaining as an Alternative to Forced Unwrapping

- 강제 추출의 대안으로서 옵셔널 체이닝.

-강제 추출과 같은 옵셔널 추출과는 어떤 차이가 있나?

강제 추출같은 경우 nil이라면 에러가 발생하지만, 체이닝은 값에 대한 확인과 접근만을 하기 때문에 nil이라면 nil을 반환받음.

You specify optional chaining by placing a question mark (?) after the optional value on which you wish to call a property, method or subscript if the optional is non-nil. This is very similar to placing an exclamation point (!) after an optional value to force the unwrapping of its value. The main difference is that optional chaining fails gracefully when the optional is nil, whereas forced unwrapping triggers a runtime error when the optional is nil.

-> 옵셔널 체이닝은 옵셔널 값 뒤에 ?를 붙임으로서 할 수 있다. 프로퍼티, 메소더, 서브스크립트에 가능하다. 이것은 마치 강제추출할 때 뒤에 !를 붙이는 것과 비슷한 모양새이다. 그러나 가장 큰 차이점은 옵셔널 체이닝은 nil 옵셔널의 값이라면 nil을 반환 받는다는 것이다.

 

-옵셔널 바인딩과의 차이

둘다 값에 대해 안전하게 접근할 수 있다는 공통점이 있고 딱히 차이는 없어보인다. 다만 바인딩은 값을 직접 추출해 사용할 수 있다는 것?

그리고 체이닝의 문법이 훨씬 간단하는 것.

' IOS,Swift > Swift⌘' 카테고리의 다른 글

Swift - Collection Type2 Dictionaries  (0) 2022.07.02
Swift - Optional  (0) 2022.07.01
Swift - Enumeration  (0) 2022.06.30
Swift - Collection Type1 Array  (0) 2022.06.28
Swift - Declaring Constants(let) & Variables(var)  (0) 2022.06.26