0
0
Swiftprogramming~10 mins

Optional chaining with ?. 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 access the street name using optional chaining.

Swift
let streetName = person.address[1]street
Drag options to blanks, or click blank then click option'
A?.
B!
C.
D->
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.' instead of '?.' causes a compile error if the optional is nil.
Using '!' forces unwrapping and can cause runtime crashes.
2fill in blank
medium

Complete the code to call the optional method safely using optional chaining.

Swift
let result = person.delegate[1]performAction()
Drag options to blanks, or click blank then click option'
A!
B?.
C->
D.
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.' causes compile error if delegate is nil.
Using '!' can cause runtime crash if delegate is nil.
3fill in blank
hard

Fix the error in safely accessing the nested optional property.

Swift
let zipCode = person.address[1]postalCode[2]code
Drag options to blanks, or click blank then click option'
A?.
B.
C!
D->
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.' for the first optional causes compile error.
Using '!' can cause runtime crash if optional is nil.
4fill in blank
hard

Fill both blanks to safely access the city name from an optional nested property.

Swift
let city = person[1]address[2]city
Drag options to blanks, or click blank then click option'
A?.
B.
C!
D->
Attempts:
3 left
💡 Hint
Common Mistakes
Using '.' for the optional property causes errors.
Using '!' risks runtime crashes if the optional is nil.
5fill in blank
hard

Fill all three blanks to safely call a method on an optional delegate's optional property.

Swift
let value = person[1]delegate[2]optionalProperty[3]computeValue()
Drag options to blanks, or click blank then click option'
A?.
B.
D!
Attempts:
3 left
💡 Hint
Common Mistakes
Using '!' can cause runtime crashes if any optional is nil.
Using '.' for optional properties causes compile errors.