What is the use of the double question mark “??” in Swift?


In this tutorial, you will learn the use of double question marks (?) in the Swift language.

In Swift, a double question mark (??) is called the "nil−coalescing operator". This operator is basically used to provide a default value in the case of nil. In other words, when a variable is nil and you want to provide a default value in the absence of a value, use this operator.

According to Apple documentation

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

Syntax

a != nil ? a! : b

According to syntax, if value a is not equal to nil, it will return a wrapped value of a or−else value b will be returned. Here value b will be of the same type as type a.

Basic Signature

We can understand how this operator works internally by using the below syntax −

public func ?? (optional: T?,
defaultValue: @autoclosure () throws -> T) rethrows -> T {
   switch optional {
      case .some(let value):
      return value
      case .none:
      return try defaultValue()
   }
}

Let's understand this with some examples 

Example

// declaring a student structure
struct Student {

   // student properties
   var name: String?
   var age: Int?
   var score: Double?
   
   // created a function to display the student information
   func displayInformation() {
      print("Name: \(name ?? "NA")")
      print("Age: \(age ?? 18)")
      print("Score: \(score ?? 0.0)")
   }
}

// created an object called amit
let amit = Student(name: "Amit Sharma", age: nil, score: 8.9)

// displaying information
amit.displayInformation()

Output

Name: Amit Sharma
Age: 18
Score: 8.9

Explanation

In the above example, you can see we are displaying default values in case of no value. As age is nil in this case, we are passing a default value in the absence of a nil value.

Lastly, there are some other operators in the Swift language that are similar to the nil-coalescing operator. Let's understand the basic difference between them to avoid confusion.

Difference between them

  • Single question mark (?)

  • It is used to make the variable an optional type. It is written just after the variable name.

  • Double question marks (??)

  • It is used to provide the default value. It is also called the nil-coalescing operator.

  • Single question mark with a colon (?:)

  • This operator is called the ternary operator. It is used to execute the flow of the statement. Basically, you can say it is a short form of an if-else statement. Using this you can match multiple conditions and return values accordingly.

  • Optional Chaining (?.)

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

Conclusion

This operator is very useful to provide a default value in case of nil. Many times, you deal with optional variables in the code, and to handle the nil value, this operator works perfectly. It makes code readable and concise.

If you have a code that requires a default value, don't hesitate to use this operator.

Updated on: 09-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements