Default vs Optional vs Explicit Non-nil Variables: Swift


In Swift, we can differentiate the variables into three different categories based on their possible values.
The variable can be of default type, optional type or an explicit non-nil type.

All three types of variables can be clubbed with both let and var. Or they can also be used with any data type.
Before looking at their differences, Let's try to understand them one by one in detail.

Default Type Variable

Default type variables are the ones which need to be initialised either in the constructor or need to be declared along with the definition itself. It can be initialised with some default value and later can be changed if it's a mutable var type.

There is no separate syntax for default type variables.
If we don't initialise the variable with definition and even in the constructor, The compiler will show an error.
  
class CustomClass{

var defaultVariable: Int

var defaultVariable2: Int = -1

init(defaultVariable : Int){
self.defaultVariable = defaultVariable
}
}

Optional Type Variable

Optional type variables are the ones which can hold a nil value as well.
Initialising the optional type variables is optional at both the places ie while defining or in the constructor.
By default, the compiler will initialise the optional variable with a nil value. It can be changed to nil if the variable is of var type.

Optional variables can be defined using ? as a suffix to the variable type. Option variables require a nil check or unwrapping while using them.
  
class CustomClass{

var optionalVariable: Int?

var optionalVariable2: Int? = -1
}

Explicit Non-nil Variables

Explicit Non-nil variables are the ones which are not required to be initialised while defining the variable as well as in the construct but whenever we are going to use the variable, it will be treated as a non-optional or default type variable.
This means we don't have to add any nil check while using this variable.

In short, we tell the compiler that it will be the developer's responsibility to initialise the property before using it. If we don't initialise before using it, it will throw an NPE.
  
class CustomClass{

var explicitNonNilVariable: Int!

var explicitNonNilVariable2: Int! = -1
}

Default vs Optional vs Explicit Non-nil Variables

  • A default variable needs to be initialised while defining or in the constructor. There is no need to use a nil check while using the default variable.
  • An optional variable doesn't need to be initialised while defining or in the constructor. This will need a nil check before using it.
  • An explicit non-nil variable doesn't need to be initialised while defining or in the construct but it's the developer's responsibility to make sure that it will be non-nil before accessing it. There is no need to use a nil check while using it as well.