Bird
0
0

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:
  1. 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.
  2. 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.
  3. Final Answer:

    let mixed: [Any] = [1, "two", 3] -> Option D
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes