Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


Difference between non-nullable and nullable in swift

Sharaz Haider


Swift is a general-purpose language designed using different paradigms, introduced by Apple Inc. It is officially introduced for IOSiPhone Operating System platforms. The language has all the features of other high-level languages such as Python and Objective C. Easy and clean python-like syntax makes it easy to work with Swift APIs, code reading, and maintenance. Swift provides the ability of minimum memory usage using ARCAutomatic reference counter and inference types which makes code cleaner and mistake-free.

Non-nullable in Swift

Variables and objects in swift are non-nullable by default regardless of the underlying type. In Swift, objects and variables should be explicitly assigned some non-nullable value. Like in other languages, variables are by default assigned some matters, such as for integer 00 in C# is assumed for any non-nullable variable. Still, we have to set the value to a non-nullable explicitly.

The following code demonstrates how we can declare non-nullable variables in Swift:

var x: Int32 = 0; // non-nullable by default
var y: Int32 = 2; // non-nullable by default
Non-nullable variables in swift

Line 1: We create a variable x of type Int32 with an initial value of 00 as a non-nullable variable. If 00 is not assigned initially to variable x, it results in an error.

Line 2: We create a variable y of type Int32 with an initial value of 22 as a non-nullable variable. It is mandatory to assign a value to a variable during declaration.

Nullable in Swift

Nullable in Swift is different compared to other languages. Nullable variables and objects are created using ! and ? symbols at the end of the variable declaration.

The following code demonstrates how we can declare nullable variables in swift using ! and ?:

var x: Int32! // nullable
var y: Int32! // nullable

var x2: Int32? // nullable
var y2: Int32? // nullable
Nullable variables in swift

Line 1–2: We declare variables x and y of type Int32 as nullable using the !, which will not cause an error if no value is assigned to these variables.

Line 4–5: We declare variables x2 and y2 of type Int32 as nullable using the ?. No value is assigned to these variables during declaration.

Nullable using !

Nullable with ! is implicitly unwrapped nullable. This means if even the original value is nil, we can still use this variable in different scenarios, such as we can use it in any arithmetic operation. Still, it will throw a nil value exception at runtime.

Nullable using ?

Variables declared with ? are explicitly unwrapped nullable and cannot be used in any operation or scenario because they do not allow direct access to underlying type reference. These variables are often used for nil comparison and explicitly unwrapped to access its content.



View all Courses

Keep Exploring