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.

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

240_F_77959340_hWLiOY93juohUoXqjKzqPB79552nw8XU

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

download

Advertisements