Answer the question
In order to leave comments, you need to log in
How to solve a problem on dictionaries from a book?
If I understand the condition correctly, you need to write a function that takes a string and returns a dictionary in which the key is a character from the string, the value is how many times it is repeated in the string.
Here is the original:
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]
func occurencesOfCharacters(in text: String) -> [Character: Int] {
var dicOfChars: [Character: Int] = [:]
var i = 1
for character in text.characters {
if dicOfChars.updateValue(i, forKey: character) != nil {
dicOfChars[character] = i + 1
i += 1
} else {
i = 1
dicOfChars[character] = i
}
}
return dicOfChars
}
print(occurencesOfCharacters(in: "memerr")) // ["r": 2, "m": 2, "e": 3]
Answer the question
In order to leave comments, you need to log in
func occurencesOfCharacters(in text: String) -> [Character: Int] {
var dicOfChars: [Character: Int] = [:]
for character in text.characters {
if dicOfChars[character] != nil {
dicOfChars[character]? += 1
}
else {
dicOfChars[character] = 1
}
}
return dicOfChars
}
print(occurencesOfCharacters(in: "memerr"))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question