Swift is a general-purpose language designed using different paradigms, introduced by Apple Inc. It is officially introduced for
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 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 defaultvar y: Int32 = 2; // non-nullable by default
Line 1: We create a variable x
of type Int32
with an initial value of as a non-nullable variable. If 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 as a non-nullable variable. It is mandatory to assign a value to a variable during declaration.
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! // nullablevar y: Int32! // nullablevar x2: Int32? // nullablevar y2: Int32? // nullable
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 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.
?
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.
Free Resources