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

Optional in Swift (Easy Start with examples)

2017-06-03

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:

[gist https://gist.github.com/arkilis/eaa5c146170effaf6e1f6ed055ca003a/]

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

[gist https://gist.github.com/arkilis/39ea4a6b4fcbd1234badbfc74fcf8e3e/]

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:

[gist https://gist.github.com/arkilis/204ee365b778e576d8f5991e76204d31/]


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.

[gist https://gist.github.com/arkilis/1cb1d85da475a20f330422558f9cdada/]

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:

[gist https://gist.github.com/arkilis/956f059fc6e40205fc8ac4331b001663/]

Updated:Implicitly Unwrapped Optionals

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


Reference:

http://www.arkilis.me

arkilis

Comments: