Swift : Optionals

What is Optional in Swift ?

In Swift, variable values can be optional.

That means that a variable will either be nil or it will have a valid value.

We can declare a variable as Optional if there is a possibility that the variable may not have a valid value.

Declaring Optional variables and using it in code

We can declare a variable as Optional by putting a question mark(?) after the type. For example :

var b : Int?

Using Optional variable

If we directly use an Optional variable in an expression with other variables, it will result in an error. We will need to get the value of the variable by unboxing the Optional.

var a = 2

var b : Int? = 3 // giving a value for explaining the ! operator

var sum = a + b!

If the Optional is nil, unwrapping it using “!” will generate runtime error.

So, we should use one of the following approaches :

Checking for nil

var b : Int? = 3
if b != nil {


Using if let

var a = 2

var b : Int?

var sum : Int

if let tmpb = b {


Using guard statement

With guard statement you unbox the valid value and let the execution continue or fail and execute the guard statements

func doubleValue(value : Int?) -> Int? {
    guard let validValue = value else {
        print("the value is nil")
        return nil }
    return 2 * validValue


© 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags