Optional, Nil, and Nil Check in Swift

Updated: February 22, 2023 By: Khue Post a comment

This article is about the nil value and the Optional type in Swift.

Nil and Optional

In Swift, optional and nil are related concepts, but they are not the same thing.

Optional is a type that represents a value that may or may not exist. When you declare a variable as optional, you’re saying that the variable may contain a value of a certain type, or it may not contain a value at all. You can use an optional to handle cases where a value may not be available or may be unknown.

On the other hand, nil is a specific value that represents the absence of a value. You can use nil with any optional variable to indicate that it currently does not contain a value. It’s similar to null in other programming languages like Java, JavaScript, and Dart.

You can declare an optional variable by appending a question mark ? to its type, like this:

var optionalNumber: Int?  
var optionalString: String?

Or like this one:

var optionalNumber: Optional<Int>
var optionalString: Optional<String>

Both of the code snippets declare 2 variables:

  • optionalNumber: This can hold an integer value or be nil
  • optionalString: This can either hold a string value or be nil

Nil Check

A Nil check is the task of checking whether a variable is nil or not for the purpose of reducing errors and increasing the efficiency of the program. There are several ways to do so.

Using the == operator

You can use the == operator to compare the optional variable to nil. Let’s take a look at the example below:

var optionalValue: Int?

if optionalValue == nil {
    print("Optional value is nil")
} else {
    print("Optional value is \(optionalValue!)")
}

Output:

Optional value is nil

You can also use the ternary operator to provide a default value in case the optional value is nil:

var optionalValue: Int?
let value = optionalValue != nil ? optionalValue! : 0
print("Value is \(value)")

You can also use the guard statement to exit early if the optional value is nil:

func myFunction(_ value: String?) {
    guard value != nil else {
        print("Optional value is nil")
        return
    }

    print("Optional value is \(value!)")
}

myFunction(nil)

Output:

Optional value is nil

Using the ?? operator

Another way to handle nil values in Swift is to use the ?? operator (also known as the nil coalescing operator). This operator provides a default value to use if the optional value is nil.

Example:

var optionalValue: String? = nil
let value = optionalValue ?? "Sling Academy"
print("Value is \(value)")

Output:

Value is Sling Academy

Using optional chaining

Optional chaining is a powerful feature of Swift that allows you to chain multiple operations together in a way that gracefully handles nil values. You can use a question mark ? to chain the property, method, or subscript call onto the optional value. If the optional value is NOT nil, the call is executed, and the result is returned as an optional value. If the optional value is nil, the entire expression evaluates to nil, and the call is not executed.

Example:

struct Person {
    var name: String?
}

let person: Person? = Person(name: "Alice")

if let personName = person?.name {
    print("Person's name is \(personName)")
} else {
    print("Person is nil or has no name")
}

Output:

Person's name is Alice

Using the ! operator

The ! operator can be used to force-unwrap an optional value, but it should be used with caution because if the optional value is nil, it will result in a runtime error.

Example:

var optionalValue: String? = "Hello, Swift!"

if optionalValue == nil {
    print("Optional value is nil")
} else {
    let value = optionalValue!
    print("Optional value is \(value)")
}

Output:

Optional value is Hello, Swift!