Chapter 7-challenge 10: counts The characters

I do not understand how the line if let count = occurrences[character]

because count is an Int, and occurrences[character] is a Character

how the fuction compares a single character of the string to each other??

Declare a function occurrencesOfCharacters that calculates which characters occur in a string, as well as how often each of these characters occur. Return the result as a dictionary. This is the function signature:

func occurrencesOfCharacters(in text: String) → [Character: Int]

Hint: String is a collection of characters that you can iterate over with a for statement.

func occurrencesOfCharacters(in text: String) → [Character: Int] {
var occurrences: [Character: Int] = [:]
for character in text {
if let count = occurrences[character] {//How comprare a string with a number
occurrences[character] = count + 1
} else {
occurrences[character] = 1
return occurrences

@anzo73 occurrences[character] returns either nil for the very first occurrence of character in text or the actual number of previous occurrences of character in text otherwise.

You either set occurrences[character] to 1 if its value is nil or update count if occurrences[character] returns a non-nil value for each character in the string.

Please let me know if you have any other questions or issues about the whole thing when you get a chance. Thank you!

This topic was automatically closed after 166 days. New replies are no longer allowed.