Nil Coalescing Operator
Part of the Fundamentals section of Coddy's Swift journey — lesson 14 of 86.
Sometimes you just want to provide a default value when an optional is nil, without writing multiple lines of code. Swift's nil coalescing operator (??) does exactly that — it unwraps an optional if it has a value, or returns a default value if it's nil.
let nickname: String? = nil
let displayName = nickname ?? "Guest"
print(displayName) // GuestSince nickname is nil, the operator returns "Guest" instead. If nickname had a value, that value would be used.
let username: String? = "SwiftCoder"
let greeting = username ?? "Anonymous"
print(greeting) // SwiftCoderThe nil coalescing operator is perfect for one-liners where you need a fallback value. It's cleaner than writing an if let statement when you simply want to substitute nil with a default. The result is always a non-optional value, so you can use it directly without further unwrapping.
Challenge
EasyWrite a function getDisplayName that takes an optional username and a defaultName, then returns the appropriate display name using the nil coalescing operator.
If the username is empty (represented by an empty string ""), treat it as nil and return the default name. Otherwise, return the username.
Parameters:
username(String): The user's name (empty string represents nil)defaultName(String): The fallback name to use
Returns: The username if it's not empty, otherwise the defaultName.
Hint: Convert the username to an optional inside your function — if it's empty, make it nil. Then use ?? to provide the fallback.
Cheat sheet
The nil coalescing operator (??) unwraps an optional if it has a value, or returns a default value if it's nil:
let nickname: String? = nil
let displayName = nickname ?? "Guest"
print(displayName) // GuestIf the optional has a value, that value is used instead:
let username: String? = "SwiftCoder"
let greeting = username ?? "Anonymous"
print(greeting) // SwiftCoderThe result is always a non-optional value, making it cleaner than if let for simple fallback scenarios.
Try it yourself
func getDisplayName(username: String, defaultName: String) -> String {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic Input