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.
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”
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
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
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.
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.
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 :).
Comments powered by Disqus.