Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to cast the variable to String using safe casting.
Swift
let anyValue: Any = "Hello" let stringValue = anyValue [1] String
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
as without optional, which causes a compile error.Using
is which only checks type but does not cast.✗ Incorrect
Use as? for safe optional casting in Swift.
2fill in blank
mediumComplete the code to force cast the variable to Int.
Swift
let anyValue: Any = 42 let intValue = anyValue [1] Int
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
as? which returns an optional instead of force casting.Using
as which is for upcasting or bridging.✗ Incorrect
Use as! to force cast when you are sure of the type.
3fill in blank
hardFix the error in the code by choosing the correct casting operator.
Swift
let anyValue: Any = 3.14 let doubleValue = anyValue [1] Double
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
as which causes a compile-time error here.Using
as! which can crash if the cast fails.✗ Incorrect
Use as? for safe casting to avoid runtime errors.
4fill in blank
hardFill both blanks to cast and unwrap safely.
Swift
if let stringValue = anyValue [1] String [2] { print("Value is \(stringValue)") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
as! which is unsafe here.Using
is which does not cast.✗ Incorrect
Use as? for safe casting and else for the else block.
5fill in blank
hardFill all three blanks to cast an array element safely and print it.
Swift
let items: [Any] = ["apple", 5, 3.14] if let firstItem = items[0] [1] String [2] { print("First item: \(firstItem) with length \(firstItem[3])") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
as! which can crash if the cast fails.Using
is instead of casting.Trying to use
length instead of count.✗ Incorrect
Use as? for safe casting, else for the else block, and count to get the string length.