0
0
Swiftprogramming~20 mins

Array creation and type inference in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Array Mastery
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?

Consider the following Swift code that creates an array using type inference. What will be printed?

Swift
let numbers = [1, 2, 3, 4]
print(type(of: numbers))
AArray<Int>
BArray<String>
CDictionary<Int, Int>
DSet<Int>
Attempts:
2 left
💡 Hint

Look at the values inside the array and what type Swift infers from them.

Predict Output
intermediate
2:00remaining
What is the output of this Swift array creation?

What will this Swift code print?

Swift
let mixedArray = ["apple", "banana", "cherry"]
print(type(of: mixedArray))
AArray<String>
BArray<Int>
CArray<Any>
DArray<Character>
Attempts:
2 left
💡 Hint

All elements are strings, so what type does Swift infer?

Predict Output
advanced
2:00remaining
What is the output of this Swift code with mixed types?

What will this Swift code print?

Swift
let mixed = [1, 2.5, 3]
print(type(of: mixed))
AArray<Int>
BArray<Double>
CArray<Any>
DArray<Float>
Attempts:
2 left
💡 Hint

Swift will promote integers to a common type with the floating-point numbers.

Predict Output
advanced
2:00remaining
What error does this Swift code raise?

What error will this Swift code produce?

Swift
let invalidArray = [1, "two", 3]
print(type(of: invalidArray))
AArray<Int>
BArray<String>
CError: Heterogeneous types in array without explicit type annotation
DArray<Any>
Attempts:
2 left
💡 Hint

Swift arrays must have elements of the same type or an explicit common type.

🧠 Conceptual
expert
2:00remaining
How does Swift infer the type of an empty array literal?

Given the code let empty = [], what is the inferred type of empty in Swift?

AArray<Int>
BArray<Any>
CIt causes a compile-time error due to ambiguous type
DArray<String>
Attempts:
2 left
💡 Hint

Think about how Swift needs type information to infer the type of an empty array.