chevron-up bell reply instagram twitter2 feed3 finder search-25px-p0

Optional in Swift (Easy Start with examples)


Optional in Swift
Swift is designed as a type Safe language. With the introduction of Optional, Swift solved the issue that variable can be nil or not in Objective-C, which makes the code more robust and safe. Optional is like a box, you can put normal type (Int, String, object) into the box, or Optional itself.

The above code will pop up an error when trying to assign a nil to sz, Error msg:

This issue can be eliminated by make variable sz as an optional type.

Variable can be nil

Swift check the running type at compile time:

The following examples shows adding a string to a optional:


To get the optional value, it was called unwrap optional.


A runtime error happened, as it is impossible to have a string added to a nil, so the right way of writing the optional and unwrap it is:


Optional Binding

Instead of using forced unwrapping, swift does provide a more convenient way of unwrapping an optional by using a temporary constant or variable.


Choose either var tempPrice or let tempPrice is depend on whether do you want to update this value in the if block.

Optional Chaining

When an optional object has an optional property, you can use Optional Chaining to unwrap it:


Updated:Implicitly Unwrapped Optionals

Implicitly Unwrapped Optionals are optionals that can be automatically unwrapped. Examples: