0
0
Swiftprogramming~20 mins

Why Swift is strongly typed - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Strong Typing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Swift code with type safety?

Consider this Swift code snippet. What will it print?

Swift
let number: Int = 10
let text: String = "20"
// What happens if we try to add number + text?
// print(number + text) // Uncommenting this line causes an error

print(number)
ACompilation error
B30
C10
D1020
Attempts:
2 left
💡 Hint

Swift does not allow adding an Int and a String directly.

🧠 Conceptual
intermediate
1:30remaining
Why does Swift require explicit type conversion?

Why does Swift require you to convert types explicitly instead of allowing implicit conversions?

ATo prevent unexpected bugs by enforcing clear type usage
BTo make the code run faster by skipping conversions
CBecause Swift does not support multiple data types
DTo allow variables to change types automatically
Attempts:
2 left
💡 Hint

Think about how clear rules help avoid mistakes in your code.

🔧 Debug
advanced
2:00remaining
What error does this Swift code produce?

Look at this Swift code. What error will it cause?

Swift
var value: Int = 5
value = "10"
ARuntime error: Invalid cast
BType mismatch error: Cannot assign String to Int
CNo error, value becomes 10
DSyntax error: Missing semicolon
Attempts:
2 left
💡 Hint

Check the variable type and the assigned value type.

Predict Output
advanced
1:30remaining
What is the output of this Swift function using strong typing?

What will this Swift function print?

Swift
func multiply(_ a: Int, _ b: Int) -> Int {
    return a * b
}

let result = multiply(3, 4)
print(result)
A12
B7
C34
DCompilation error
Attempts:
2 left
💡 Hint

Check the multiplication of 3 and 4.

🚀 Application
expert
2:30remaining
How does Swift's strong typing help prevent bugs in this scenario?

Imagine you have a function that takes a user age as an Int. What problem does strong typing help avoid?

AAutomatically converting age to a String when printing
BIgnoring the age parameter if it is zero
CAllowing the age to be negative without warning
DPassing a String like "twenty" instead of an Int, causing a compile error
Attempts:
2 left
💡 Hint

Think about what happens if you try to pass text instead of a number.