Question Mark (? vs ?. vs ?? vs ? :) in Swift

In Swift, the question mark works differently in different situations or when clubbed with some other keywords. It sometimes denotes the variable type as optional or sometimes being used for optional chaining.

Let's try to understand them in detail before looking at their differences.

Optional Variable ?

It makes the variable type optional if added as a suffix to the variable type while defining any variable. It will need a nil check before accessing the optional variable.

You can read about the different types of variables in the blog Default vs Optional vs Explicit Non-nil Variables: Swift.
The syntax will look like the below for the optional variable.
var nullableVariable: Int?

Safe Call or Optional Chaining Operator ?.

It is used to chain any optional variable or property further to other properties or functional calls.

Safe calls are useful in chaining. For example, if Bob, an Employee, may be assigned to a Department (or not), that in turn may have another Employee as a department head, then to obtain the name of Bob’s department head (if any), we write the following
let departmentHead = bob?.department?.head?.name
Such a chain returns nil if any of the properties in it is nil.

Default Value ??

The default value is used to provide the default value if the expression before the default value operator is nil.

For example in the above example where we were looking for the department head name, if the left expression is nil, we can provide the default value as below.
let departmentHead = bob?.department?.head?.name
?? "No department head found"

Ternary Operator ? :

The ternary operator is used to separate the flows for true and false conditions for a bool variable or condition. We can call functions, assign values or even executes some code block in both true and false conditions.

The syntax for the same will look like below.
let a = 10

let result = a == 10 ? "Ten" : "Some Other Value"

Difference Between ? , ?. , ?? and ? :

  • ? is used to make the variable an optional type.
  • ?. is used for optional chaining.
  • ?? is used to provide the default value.
  • ? : separates the true and false flow for any condition or bool variable.