0
0
iOS Swiftmobile~10 mins

Optionals and unwrapping in iOS 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 declare an optional String variable named name.

iOS Swift
var name: [1]
Drag options to blanks, or click blank then click option'
AOptional
BString
CString?
DOptional<String>
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the question mark and declaring it as a normal String.
Using the word Optional without the generic type.
2fill in blank
medium

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

iOS Swift
if let unwrappedName = [1] {
  print("Hello, \(unwrappedName)!")
}
Drag options to blanks, or click blank then click option'
AunwrappedName
Bname
Cname!
DOptional(name)
Attempts:
3 left
💡 Hint
Common Mistakes
Using the unwrapped variable name inside the if let condition.
Forcing unwrap with exclamation mark instead of safe unwrapping.
3fill in blank
hard

Fix the error in force unwrapping the optional age variable.

iOS Swift
let age: Int? = 25
let unwrappedAge = [1]
Drag options to blanks, or click blank then click option'
Aage!
Bage
COptional(age)
Dage?
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the exclamation mark and causing a type mismatch.
Using optional chaining instead of force unwrapping.
4fill in blank
hard

Fill both blanks to unwrap optional email and provide a default value if nil.

iOS Swift
let email: String? = nil
let userEmail = [1] ?? [2]
Drag options to blanks, or click blank then click option'
Aemail
B"noemail@example.com"
Cemail!
Dnil
Attempts:
3 left
💡 Hint
Common Mistakes
Using force unwrap instead of nil-coalescing operator.
Providing nil as the default value.
5fill in blank
hard

Fill all three blanks to unwrap optional number safely and multiply by 2.

iOS Swift
let number: Int? = 10
if let [1] = [2] {
  let result = [3] * 2
  print(result)
}
Drag options to blanks, or click blank then click option'
AsafeNumber
Bnumber
Dnumber!
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same variable name for unwrapped and optional variables.
Forcing unwrap inside if let instead of safe unwrapping.