nil 값을 가질 수 있다.


var anIntOrNothing: Int? = 42
var anIntOrNothing: Int? = nil

if anIntOrNothing != nil 
{
// anIntOrNothing has a value
}



Conditional Let Syntax 


Conditional Let Syntax에서 Optional 변수는 값이 있으면 non-optional value로 값을 리턴하고, 값이 없으면 nil을 리턴한다.


if let anInt = anIntOrNothing 
{
println("The value is \(anInt)")
}
else 
{
println("anIntOrNothing does not have a value")
}


위 코드는 아래 코드와 같은 의미


if anIntOrNothing != nil 
{
let anInt = anIntOrNothing!
println("The value is \(anInt)")
else 
{
println("anIntOrNothing does not have a value")
}



Optional Chaining


optional type에 대한 nil 체크를 간편하게 하기 위한 문법


if let presentedViewController = self.presentedViewController
{
let view: UIView = presentedViewController.view
}


위 코드를 optional chaining 을 사용하면 아래와 같다.


let view: UIView? = self.presentedViewController?.view


optional type에 ? 를 붙여서 사용한다. 

self.presentedViewController? 는 self.presentedViewController 가 nil 값이면 nil을 리턴한다. 그 뒤에 있는 .view 는 수행되지 않는다. (만약 수행 되었다면 exception이 났겠지만)

self.presentedViewController 가 nil 값이 아니면 그 뒤에 있는 .view가 수행된다.

즉, nil 참조로 인한 exception을 피하는 짧은 코드를 작성하게 된다.


주위할 점은 optional chaining의 결과값의 타입은 optional type 이라는 점이다.



Implicitly Unwrapped Optional


var alwaysAnInt: Int! = nil


해당 타입이 Optional Type 이지만 코드 내에서 명시적으로 unwrapp 하지 않고 사용할 수 있다.


class ViewController : UIViewController
{
...
@IBOutlet var textLabel: UILabel! // Connected in ViewController.xib
...
override func viewDidLoad()
{
super.viewDidLoad()
self.textLabel.text = NSLocalizedString("Hello World!", comment: "")
// Instead of (if textLabel was not implicity unwrapped):
// self.textLabel!.text = NSLocalizedString("Hello World!", comment: "")
}
}


:)

Posted by six605
,