0
0
Swiftprogramming~10 mins

Type casting with as, as?, as! 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 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'
Aas?
Bas!
Cas
Dis
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.
2fill in blank
medium

Complete 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'
Aas
Bas?
Cas!
Dis
Attempts:
3 left
💡 Hint
Common Mistakes
Using as? which returns an optional instead of force casting.
Using as which is for upcasting or bridging.
3fill in blank
hard

Fix 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'
Ais
Bas?
Cas
Das!
Attempts:
3 left
💡 Hint
Common Mistakes
Using as which causes a compile-time error here.
Using as! which can crash if the cast fails.
4fill in blank
hard

Fill 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'
Aas?
Bas!
Celse
Dis
Attempts:
3 left
💡 Hint
Common Mistakes
Using as! which is unsafe here.
Using is which does not cast.
5fill in blank
hard

Fill 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'
Aas?
Bcount
Celse
Das!
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.