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

Suneet Agrawal
2 min readMay 11, 2023

--

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.

This post was originally posted at https://agrawalsuneet.github.io/blogs/question-mark-in-swift/ and later reposted on Medium.

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 ? :

Please continue reading at https://agrawalsuneet.github.io/blogs/question-mark-in-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.

--

--