Bird
0
0

Given an array words = ["swift", "code", "test"], how can you create a dictionary where keys are indices and values are the uppercase words using enumerated()?

hard📝 Application Q8 of 15
Swift - Collections
Given an array words = ["swift", "code", "test"], how can you create a dictionary where keys are indices and values are the uppercase words using enumerated()?
Avar dict = [Int: String]() for (i, word) in words.enumerated() { dict[i] = word.uppercased() }
Bvar dict = [String: Int]() for (i, word) in words.enumerated() { dict[word] = i }
Cvar dict = [Int: String]() for word in words { dict[word.count] = word }
Dvar dict = [Int: String]() for (word, i) in words.enumerated() { dict[i] = word.lowercased() }
Step-by-Step Solution
Solution:
  1. Step 1: Understand desired dictionary structure

    Keys are indices (Int), values are uppercase words (String).
  2. Step 2: Check each option's logic

    var dict = [Int: String]() for (i, word) in words.enumerated() { dict[i] = word.uppercased() } correctly uses enumerated() to get index and word, then stores uppercase word with index key. var dict = [String: Int]() for (i, word) in words.enumerated() { dict[word] = i } reverses key-value types. var dict = [Int: String]() for word in words { dict[word.count] = word } uses word count as key incorrectly. var dict = [Int: String]() for (word, i) in words.enumerated() { dict[i] = word.lowercased() } swaps tuple order and uses lowercased().
  3. Final Answer:

    var dict = [Int: String]() for (i, word) in words.enumerated() { dict[i] = word.uppercased() } -> Option A
  4. Quick Check:

    Use enumerated() to map index to uppercase word [OK]
Quick Trick: Use enumerated() to get index and transform values [OK]
Common Mistakes:
  • Swapping key and value types
  • Using wrong tuple order
  • Not transforming word case

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes