Default vs Optional vs Explicit Non-nil Variables: Swift

Suneet Agrawal
2 min readMay 12, 2023

--

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.

This post was originally posted at https://agrawalsuneet.github.io/blogs/default-vs-optional-vs-explicit-non-nil-variables-swift/ and later reposted on Medium.

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.

Please continue reading at https://agrawalsuneet.github.io/blogs/default-vs-optional-vs-explicit-non-nil-variables-swift/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--