Introduction
The nil coalescing operator helps you provide a default value when something might be missing (nil).
The nil coalescing operator helps you provide a default value when something might be missing (nil).
optionalValue ?? defaultValue
The operator checks if optionalValue is nil.
If it is nil, it uses defaultValue instead.
name is nil, displayName becomes "Guest".let name: String? = nil let displayName = name ?? "Guest"
score has a value, finalScore uses it; otherwise, it uses 0.let score: Int? = 85 let finalScore = score ?? 0
input is not nil, message will be "Hello".var input: String? = "Hello" let message = input ?? "No message"
This program shows how the nil coalescing operator returns a default when the optional is nil, and the actual value when it is not.
var userInput: String? = nil let result = userInput ?? "Default value" print(result) userInput = "Swift is fun!" let newResult = userInput ?? "Default value" print(newResult)
The nil coalescing operator only works with optionals.
You can chain multiple nil coalescing operators for multiple fallback values.
The nil coalescing operator (??) provides a simple way to use a default value when an optional is nil.
It helps keep your code clean and safe from unexpected nil values.
?? do in Swift??? returns the optional's value if it exists; otherwise, it returns the default value provided.?? between an optional and a default value.?? correctly: let value = optionalValue ?? defaultValue.var name: String? = nil let displayName = name ?? "Guest" print(displayName)
name is nil.name ?? "Guest" returns "Guest" because name is nil.let age: Int? = 25 let userAge = age ?? print(userAge)
?? must be followed by a default value to use if the optional is nil.age ?? is incomplete because no default value is provided after ??.let scores: [String: Int?] = ["Alice": 85, "Bob": nil], which expression correctly uses the nil coalescing operator to get Bob's score or 0 if nil?Int? inside the dictionary optional lookup, so scores["Bob"] returns Int??.scores["Bob"] ?? nil ?? 0 first flattens the double optional to Int? (returns inner value or nil), then applies ?? 0 to provide 0 if nil, yielding Int. For "Bob", some(nil) ?? nil = nil, then nil ?? 0 = 0.Pass the test and this pattern moves unknown