Optional of swift

Intro

This is a category of study&&notes of swift, program and so on during the study of [Developing iOS8 Apps with Swift] on the iTunes U.
此系列为学习stanford课程:Developing iOS8 Apps with Swift过程中,对语言,程序设计,编程能力等部分的学习和记录。

Optional

The simple way to declare a optional value:

var testString: String?

It means: testString is an optional value and if testString has a value, it must be a string; if not, it is nil. Notice:

  1. only optional value can be nil
  2. optional can be available for any type, such as class, scalar
  3. using ! to unwrapped the optional value to get/set

From the above, for the normal var, we don’t need to check like:

var testString: String = "demo"
if testString {

}

It will have an error.
nil is different from that in ObjC.

During the course, there is another way to declare optional:

@IBOutlet weak var label: UILabel!

The Paul says it is called implicit optional value. The difference of optional between using ? and ! only lies in usage, for example:

var label: UILabel?
label!.text!= label!.text! + digit

var label2: UILabel!
label2.text! = label2.text! + digit
//here, UILable's text is `text?`

optional chaining

In Book [The Swift Programming Language], there is a charpt Optional Chaining, it is :

Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil.

Just grab the example from the book:

if let johnsStreet = john.residence?.address?.street {
    println("John's street name is ​\(​johnsStreet​)​.")
} else {
    println("Unable to retrieve the address.")
}
// prints "Unable to retrieve the address.”

We can use ? to get john‘s optional property residence‘s optional propery address‘s optional property street. That’s I think why it is called chaining. Notice if address is nil, it will go to the else.
There is an important thing: any method,property called in the optional chaining becomes the optional value event it is not defined as optional.

Why we need optional

In swift, nil is not a value, and hence the normal var can’t have the value of nil. But we do need leave the var empty(without value), and optional comes for that.

Comments