10. Optionals in Swift

Swift is a very modern language, it provides very nice features that other programming languages do not have. One of these features is called optionals. The purpose of these optionals is to handle all situations safely where variables or constants may not have any value.

As you know that Swift does not allow to use any variable without being initialized. The following code will give error:

var biology

error: type annotation missing in pattern, in other words initialize this variable with some value.

Swift also provides another way to declare variable without initialzation. But the problem is you cannot use them without assigning a value.

var biology : Int
println(biology)

error: variable ‘biology’ used before being initialized.

Now consider that you are writing a program to handle student final results in Swift. Consider these restrictions from Swift. If variable is not initialized, Swift will throw an error. But if you will initialize a variable biology with value 0 then logically its not correct. It means that student did not pass this subject because he got zero marks in biology.

var biology = 0
println(biology)

To handle this type of tricky situations Swift provides Optionals. Variable can be initialized as optionals by placing ‘?’ after its declaration.

var biology : Int?

At right hand side in Xcode, output window will display the output ‘nil’ which shows that variable is nil and no value is assigned yet. Try following line in Xcode

var biology : Int?
if biology != nil {
    
    println("Student got \(biology) marks in Biology")

}else{
    
    println("Biology marks are not evaluated")

}

In this example else code block will execute because you did not assign any value to variable biology. See how convenient and safe this technique, you should not be worried about the initial value of variable biology.  Now assign some value to variable biology.

var biology : Int?
biology = 50

if biology != nil {
    
    println("Student got \(biology) marks in Biology")

}else{
    
    println("Biology marks are not evaluated")

}

Once you assigned some value to variable biology, ‘if’ code block will execute and your output will be “Student got Optional(50) marks in Biology”

Forced Unwrapping

I think you have already noticed that something unexpected in your output,

Student got Optional(50) marks in Biology. Optional(50) ? 

If a variable is declared as optional and some value is assigned to it, this value is wrapped in this optional variable. You can access this value by using a concept called forced unwrapping. Place ! operator just after optional variable.

var biology : Int?
biology = 50

if biology != nil {
    
    println("Student got \(biology!) marks in Biology")

}else{
    
    println("Biology marks are not evaluated")

}

Now the output is “Student got 50 marks in Biology” .

Optional binding syntax

Swift provides another functionality to unwrap the optional variable. In if statement you can assign value to a constant. If optional variable is not nil, value will be assigned to a constant and you can print this constant without ! operator.   

if let marks = biology {

    println("Student got \(marks) marks in Biology")

} else {

    println("Marks are not assigned")

}

Continue with Optionals.

 

Download file from GitHub