P
P
Pavel2017-06-30 22:39:37
Swift
Pavel, 2017-06-30 22:39:37

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]

As you can see, I have a problem with the variable i, in which I keep track of the number of repetitions of a character.
Or it just needs another solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2017-06-30
@pavelsazonov

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 question

Ask a Question

731 491 924 answers to any question