Optional and Unwrapping in swift

What is optional type in Swift?

An optional type basically means that the variable can be nil. optional is indicated by question mark (?)

Variable with optional type

var someNumber : Int? = 4  // The (?) indicates that someNumber can be nil
someNumber = nil  //can assign nil value to optional variable

Variable without optional type

var someNumber : Int = 4
someNumber = nil   // nil cannot be assign to type Int  //Can not do this

What is unwrapping?

To get the value from variable if it is optional, we have to unwrap it. This just means putting an exclamation point (!) at the end.

Force Unwrapping

If we declare variable as optional and if we want to use that variable we have to forcefully unwrap it.

var someNumber : Int? = 4
print(someNumber)  // "optional(4)" //without unwrap
print(someNumber!)  // 4 //with unwrap

Automatic Unwrapping

If we unwrap variable before hand we can assign nil value to variable also we don’t have to unwrap variable explicitly.

var someNumber : Int! = 4
print(someNumber)  // 4 //automatic unwrap

If we unwrap value beforehand it should not be nil.

var someNumber : Int?
someNumber = nil
print(someNumber)  // "nil"
var someNumber : Int!
someNumber = nil
print(someNumber)  // gives error 


Hope you find this blog useful. Please feel free to contact with me in case you have any query, suggestions.  You can comment, like and follow posts.

You can request any topic related to Swift and iOS development.

Donate any small amount you think for this knowledge to grow this forum.                        

To Donate –  paypal.me/SandeshSardar


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s