Home Swift ?? (Nil Coalescing) Do's and Don't
Post
Cancel

Swift ?? (Nil Coalescing) Do's and Don't

Basics

Optional is one of the fundamental safety features provided in Swift. It is a container for a value of a particular type. We are using the term container here because it means it may contain a value or not. Nil coalescing ?? is an operator used to provide a default if the optional is empty.

How to use it?

Add default value after the ?? operator following Optional.

 var name: String?
 let displayName = name ?? "NA"
 print("name is:\(displayName)")

In this case, if the name is not available then “name is NA” will be printed. In Swift, we need to always take care while unwrapping an Optional as it might crash the application. The Nil coalescing ?? operator does the Job for you if it finds the optional has no value then it uses a default instead.

Do’s and Don’t with ??

Following are some of the uses I have seen in the code and we go through them one by one and discuss the case:

(i) Requirement is if Name is not present then display “NA”

 var name: String?
 let displayName = name ?? "NA"
 print("name is:\(displayName)")

My View: Do it: is correct usage as we provide the default value if it does not exist.

(ii) Requirement is to get the number of rows in the selected section

    func indexPathOfTableView() {
        var selectedIndexPath: IndexPath?
        //Assing a value in code somewhere
        selectedIndexPath = IndexPath(section: 1, row: 0)
        
        //Uses of the indexPath
        tableView?.numberOfRows(inSection: selectedIndexPath?.section ?? 0)
    }

My View: Avoid it - Zero(0) is not the section’s default value and can also cause an unexpected issue If the index path is nil.

(iii) Requirement is to fetch a random student from the list

    func randomStudent() {
        var randomStudent: Student?
        //Assign Value to the random student in code
        
        //Somewhere in code
        let selectedStudent = randomStudent ?? Student()
        if selectedStudent.name.count > 0 {
        }
    }

My View: Avoid it - In this case, a student object without referring to any student is not a correct usage it is not a default value. It can cause an issue or crash if you are expecting a real object and get this value.

(iv) Requirement is to fetch all student names.

    struct Student {
        var name: String
    }
    
    func fetchAllNames() {
        var students: [Student]?
        //All student Name
        let studentNames = students?.map { $0.name ?? "" }
        print("All Student Names:\(studentNames)")
    }

My View: Avoid it - The task involves retrieving all student names. If a student isn’t found in the records, don’t fallback to assigning an empty string(“”). Instead, adhere to an agreed-upon default value or raise an exception indicating that the name doesn’t exist.

(v) Requirement is to check whether the student list exists.

   func checkStudentExist() -> Bool {
        var students: [Student]?
        //check student exist
        if students?.count ?? 0 > 0 {
            return true
        }
        return false
    }

My View: Avoid it - The task is to verify the existence of the student list. Using the default value in the if students?.count ?? 0 > 0 condition simplifies the check. Nevertheless, I believe it compromises readability.

What’s Next?

Nil Coalescing is a nice addition in Swift and we should use it to provide default value. However, using it as an alternative to avoid if let can be overkill or make code buggy.

Thanks for reading! I’d love to hear your thoughts on this article :).

This post is licensed under CC BY 4.0 by the author.

Game - Save Trees

Flutter on Apple Silicon Mac: Cocoa-pods Issue

Comments powered by Disqus.