Optional이란
optional은 enum이다. (An Optional is just an enum.)
Swift
enum Optional<T> // <T> is a generic like as in Array<T>
case None
case Some(T)
}
Array와 같은 일반적인 타입이다.
의 의미는 옵셔널이 모든 타입의 옵셔널이 될 수 있다는 뜻
? and !
Swift
let x: String? = nil
... is ...
let x = Optional<String>.None
let x: String? = "hello"
... is ...
let x = Optional<String>.Some("hello")
var y = x!
... is ...
switch x {
case Some(let value): y = value
case None: // raise an exception
}
추출을 한다면 x에 대한 switch가 된다. (옵셔널을 추출해서 연관값을 가져오는 방법이 switch)
x의 switch를 만들어서 Some case에는 let value를 해서 연관값을 가져오도록하고, y에 그 값을 넣어준다.
None이 되는 경우는 앱이 충돌한다. (할당되지 않은 옵셔널을 추출하는 것은 충돌이 나게 되어있다.)
if let
Swift
let x: String? = ...
if let y = x {
// do something with y
}
... is ...
switch x {
case .Some(let y):
// do something with y
case .None:
break;
}
if let
을 하는 경우에는 x에 switch 조건을 주되
Some case에서는 저 y값을 가져와서 y를 사용하는 코드를 넣어주면 if let이 여기서 동작하게 된다.
None case에서는 switch 밖으로 나가서 아무것도 하지 않는다.
Optional은 체이닝이 가능하다.(Optionals can be “chained”.)
Swift
var display: UILabel? // imagine this is an @IBOutlet without the implicit unwrap!
if let label = displau {
if let text = label.text {
let x = text.hashValue
...
}
}
... is ...
if let x = display?.text?.hashValue {
...
}
옵셔널을 선언할 때가 아니라 값을 사용하려 할 때
?
를 사용하게 되면 일단 추출을 시도해보고 추출할 수 있다면 그 값을 이용해서 다음걸로 이동하고 추출할 수 없다면 이 전체 표현에서 nil을 반환한다.(이 중에서 어느 지점에서든지 추출했을 때 nil을 반환하는 걸로 밝혀진다면)
let x 는 옵셔널 Int 타입이다.
Operator ??
There is also an Optional “defaulting” operator ??
Swift
let s: String? = ... // might be nil
if s != nil {
display.text = s
} else {
display.text = " "
}
... can be expressed much more simply this way ...
display.text = s ?? " "
s가 nil이 아니라면 값이 추출되어서 사용될거고, 그렇지 않다면 “ “ 빈 공간으로 두겠다는 뜻.