Unwrapping With If Let
Part of the Fundamentals section of Coddy's Swift journey — lesson 12 of 86.
To safely access the value inside an optional, we use if let — a technique called optional binding. This checks if the optional contains a value and, if so, unwraps it into a temporary constant.
var username: String? = "Swift_Dev"
if let name = username {
print("Welcome, \(name)")
} else {
print("No username found")
}
// Welcome, Swift_DevHere, if let checks whether username has a value. Since it does, the value is unwrapped into name, which exists only inside the if block. If username were nil, the else block would run instead.
var age: Int? = nil
if let unwrappedAge = age {
print("Age is \(unwrappedAge)")
} else {
print("Age not provided")
}
// Age not providedSince age is nil, the condition fails and the else block executes. This prevents crashes that would occur if we tried to use a missing value directly.
Challenge
EasyYou are provided with the following variable:
var nickname: String? = "CoddyLearner"Use if let to safely unwrap nickname. If it contains a value, print Hello, [value]! where [value] is the unwrapped nickname. If it's nil, print No nickname set.
Cheat sheet
Use if let (optional binding) to safely unwrap an optional and access its value:
var username: String? = "Swift_Dev"
if let name = username {
print("Welcome, \(name)")
} else {
print("No username found")
}
// Welcome, Swift_DevIf the optional contains a value, it's unwrapped into a temporary constant that exists only inside the if block. If the optional is nil, the else block executes:
var age: Int? = nil
if let unwrappedAge = age {
print("Age is \(unwrappedAge)")
} else {
print("Age not provided")
}
// Age not providedTry it yourself
var nickname: String? = "CoddyLearner"
// TODO: Write your code below
// Use if let to safely unwrap nickname
// If it contains a value, print "Hello, [value]!"
// If it's nil, print "No nickname set"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