Bird
0
0

Given a string sentence, how can you create a dictionary mapping each unique Character to its count in the string?

hard📝 Application Q9 of 15
Swift - Data Types
Given a string sentence, how can you create a dictionary mapping each unique Character to its count in the string?
AUse <code>sentence.countCharacters()</code>
BUse <code>sentence.reduce(into: [:]) { counts, char in counts[char] = 1 }</code>
CUse <code>sentence.characters.count()</code>
DUse <code>Dictionary(sentence.map { ($0, 1) }, uniquingKeysWith: +)</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to count characters

    Mapping each character to 1 and combining duplicates by summing counts creates a frequency dictionary.
  2. Step 2: Analyze options

    Use Dictionary(sentence.map { ($0, 1) }, uniquingKeysWith: +) uses Dictionary(_:uniquingKeysWith:) with + to sum counts correctly. Use sentence.reduce(into: [:]) { counts, char in counts[char] = 1 } overwrites counts instead of summing. Options A and D are invalid methods.
  3. Final Answer:

    Use Dictionary(sentence.map { ($0, 1) }, uniquingKeysWith: +) -> Option D
  4. Quick Check:

    Use Dictionary with uniquingKeysWith: + to count characters [OK]
Quick Trick: Map chars to 1, then sum duplicates with uniquingKeysWith [OK]
Common Mistakes:
  • Overwriting counts instead of summing
  • Using non-existent string methods
  • Confusing character count with string length

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes