0
0
Swiftprogramming~10 mins

Optional binding with if let in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to safely unwrap the optional using if let.

Swift
var name: String? = "Alice"
if [1] unwrappedName = name {
    print("Hello, \(unwrappedName)!")
}
Drag options to blanks, or click blank then click option'
Alet
Bvar
Cis
Dguard
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'var' instead of 'let' in the if statement.
Using 'is' which is for type checking, not unwrapping.
2fill in blank
medium

Complete the code to unwrap the optional and print the value.

Swift
var age: Int? = 30
if let unwrappedAge = [1] {
    print("Age is \(unwrappedAge)")
}
Drag options to blanks, or click blank then click option'
AunwrappedAge
Bage
CoptionalAge
Dself.age
Attempts:
3 left
💡 Hint
Common Mistakes
Using the unwrapped variable name inside the if let condition.
Using a variable name that does not exist.
3fill in blank
hard

Fix the error in the optional binding syntax.

Swift
var city: String? = "Paris"
if [1] city = city {
    print("City is \(city)")
}
Drag options to blanks, or click blank then click option'
Ais
Bvar
Cguard
Dlet
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' without 'let' or 'var' in the if statement.
Using 'is' which is for type checking.
4fill in blank
hard

Fill both blanks to unwrap two optionals and print their values.

Swift
var firstName: String? = "John"
var lastName: String? = "Doe"
if [1] first = firstName, [2] last = lastName {
    print("Full name: \(first) \(last)")
}
Drag options to blanks, or click blank then click option'
Alet
Bvar
Cis
Dguard
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing 'let' and 'var' in the same if statement.
Using 'is' instead of 'let' for binding.
5fill in blank
hard

Fill all three blanks to unwrap an optional, check a condition, and print the result.

Swift
var score: Int? = 85
if [1] unwrappedScore = score, unwrappedScore [2] 80, unwrappedScore [3] 100 {
    print("Great score: \(unwrappedScore)")
}
Drag options to blanks, or click blank then click option'
Alet
B>
C<=
Dvar
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'var' instead of 'let' for unwrapping.
Using wrong comparison operators.