You want to create an array that holds either integers or strings in Swift. Which approach correctly creates such an array?
hard📝 Application Q15 of 15
Swift - Collections
You want to create an array that holds either integers or strings in Swift. Which approach correctly creates such an array?
Alet mixed = Array<Int | String>()
Blet mixed = [1, "two", 3]
Clet mixed: [Int | String] = [1, "two", 3]
Dlet mixed: [Any] = [1, "two", 3]
Step-by-Step Solution
Solution:
Step 1: Understand Swift's type system for mixed arrays
Swift does not support union types like Int | String. To hold different types, use the type Any.
Step 2: Check each option for correctness
let mixed: [Any] = [1, "two", 3] declares mixed as [Any] and initializes with Int and String values, which is valid. let mixed = [1, "two", 3] tries to infer type but fails due to mixed types. Options A and C use invalid syntax for union types.
Final Answer:
let mixed: [Any] = [1, "two", 3] -> Option D
Quick Check:
Mixed types array uses [Any] [OK]
Quick Trick:Use [Any] for arrays with mixed types [OK]
Common Mistakes:
Trying to infer mixed types without [Any]
Using invalid union type syntax
Assuming Swift allows Int | String type
Master "Collections" in Swift
9 interactive learning modes - each teaches the same concept differently