Optional is defined in Swift as an enumeration 

enum Optional<T> {

case None 

case Some(T)


None is name for nil

let's understand optional by an example:

suppose we create a class

Class MyRectagle {

var width;

var height;


if you compile this class it generates error! because width and height are not defined which type are; Int?double? so we have two solution either initialize them or uses optionals! like that :

Class MyRectagle {

var width?;

var height?;


here it says these two variables are automatically initialized to nil so it can be compiled!


The nil coalescing operator (a ?? b):

The nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. 

The expression a is always of an optional type. The expression b must match the type that is stored inside a.

The nil coalescing operator is shorthand for the code below:

a != nil ? a! : b


let defaultColorName = "red"

var userDefinedColorName: String?   // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName

// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"


When we declare a variable as optional , we cannot force unwraping it until it's not nil


var v1 : String?

let v2 = v1! //error, v1 is optional and cannot be force unwraping

// correction

if let v3 = v1 {

    print("v1 is not nil")



    print("v1 is nil")


 © Xosrov 2016