-5
let input = "aa bb c"
let expected: [Character: Int] = [
            "a": 2,
            "b": 2,
            "c": 1,
        ]

Heres my code. Any idea what I may be doing wrong?

func createCounter(string: String) {
    var charArr: [Character] = []
    let mappedChar = charArr.map { ($0, 1)}
    let counts = Dictionary(mappedChar, uniquingKeysWith: +)
    
    for char in string {
        if (char != " ") {
            charArr.append(char)
        }
    }
    
    print(counts)
    
}
koen
  • 5,383
  • 7
  • 50
  • 89
AceEzra
  • 11
  • 2

1 Answers1

-1

I figured it out all I need to do was create a new string without the empty spaces, create and empty dictionary and loop over the new string. Heres my new code.

    var newString: String = ""
    var countDict: [Character: Int] = [:]
    
    for char in string {
        if (char != " ") {
            newString.append(char)
        }
    }
    
    for char in newString {
        if (countDict[char] != nil) {
            countDict[char]! += 1
        } else {
            countDict[char] = 1
        }
    }
    
    print(countDict)
    
}
AceEzra
  • 11
  • 2