0
0
Swiftprogramming~20 mins

Type inference by the compiler in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Type Inference 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 using type inference?

Consider the following Swift code snippet. What will be printed?

Swift
let number = 42
let message = "The answer is \(number)"
print(message)
A42
BThe answer is number
CThe answer is 42
DError: Cannot infer type
Attempts:
2 left
💡 Hint

Look at how Swift infers the type of number and uses string interpolation.

Predict Output
intermediate
2:00remaining
What type does the compiler infer for this variable?

Given this Swift code, what type does the compiler infer for value?

Swift
let value = 3.14
AString
BFloat
CInt
DDouble
Attempts:
2 left
💡 Hint

Swift defaults to a certain floating-point type when no explicit type is given.

🔧 Debug
advanced
2:00remaining
Why does this Swift code cause a compile error?

Examine the code below. Why does the compiler produce an error?

Swift
let x = nil
print(x)
Aprint requires a non-optional argument
BCannot infer type for nil without explicit type annotation
Cnil is not allowed in Swift
Dx is immutable and cannot be printed
Attempts:
2 left
💡 Hint

Think about what type nil represents and how Swift infers types.

Predict Output
advanced
2:00remaining
What is the inferred type and output of this Swift closure?

Consider this Swift code snippet. What is the inferred type of increment and what will be printed?

Swift
let increment = { (number: Int) in number + 1 }
print(increment(5))
AType: (Int) -> Int, Output: 6
BType: (Int) -> Int, Output: 5
CType: (Int) -> Void, Output: 6
DType: () -> Int, Output: 6
Attempts:
2 left
💡 Hint

Look at the closure parameter and return expression.

🧠 Conceptual
expert
2:00remaining
How does Swift's type inference handle mixed numeric literals in an expression?

What is the inferred type of result in the following Swift code?

let result = 5 + 3.0
ADouble
BInt
CFloat
DError: Cannot mix Int and Double without casting
Attempts:
2 left
💡 Hint

Swift promotes numeric types to the more general type in mixed expressions.