옵셔널(optional)이란 값이 있을 수도 ,없을 수도(nil) 있다는 뜻.
옵셔널(optional)로 사용하기 위해서는 ?를 붙여주면 된다.
// 변수 name에는 무조건 string 타입이 들어가야 함
var name: String = "kiki"
// 변수 age는 옵셔널 Int 타입으로 Int 타입의 값이 들어가거나 혹은 값이 없는 경우 nil 두 경우가 있다.
var age: Int?
Optional 인스턴스의 값을 안전하게 푼 다음 가져오기 위해 옵셔널 바인딩, 옵셔널 채이닝을 사용.
옵셔널 바인딩?
- Optional 인스턴스의 래핑된 값을 새 변수에 조건부로 바인딩하는 것.
- if let, guard let, and switch를 사용
let imagePaths = ["star": "/glyphs/star.png",
"portrait": "/images/content/portrait.jpg",
"spacer": "/images/shared/spacer.gif"]
// 딕셔너리에서 키값(key)을 통해 value를 꺼내오면, 그 반환값은 기본적으로 옵셔널(Optional)임.
// 딕셔너리에 존재하지 않는 키값이 입력되면 nil 이 반환될 수 있기 때문이다.
if let starPath = imagePaths["star"] {
print("The star image is at '\(starPath)'")
} else {
print("Couldn't find the star image")
}
// Prints "The star image is at '/glyphs/star.png'"
옵셔널 채이닝?
- 래핑된 인스턴스의 속성과 메서드에 안전하게 액세스하려면 postfix ? 를 사용.
if imagePaths["star"]?.hasSuffix(".png") == true {
print("The star image is in PNG format")
}
// Prints "The star image is in PNG format"
참고자료:
https://developer.apple.com/documentation/swift/optional
'Swift & SwiftUI' 카테고리의 다른 글
| CS 193p Lecture 3~4 정리 (0) | 2023.11.22 |
|---|---|
| Networking for beginners (0) | 2023.10.11 |
| 사용자의 위치정보 가져오기 (0) | 2023.10.05 |
| Grid (0) | 2023.09.18 |
| TextField (0) | 2023.09.10 |