# Character Count Function Recursively

**URL:** <https://forums.swift.org/t/character-count-function-recursively/51488>\
**Category:** Using Swift\
**Tags:** swift\
**Created:** [August 25, 2021, 3:26pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488 "2021-08-25T15:26:03Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![hairyyak](https://avatars.discourse-cdn.com/v4/letter/h/bbce88/32.png) [@hairyyak](https://forums.swift.org/u/hairyyak)\
**Post date:** [August 25, 2021, 3:26pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/1 "2021-08-25T15:26:03Z")

</div>

```swift
//
// main.swift
// TmpProj
//
// Created by Mark King on 24/08/2021.
//

import Foundation

func occurencesOfCharacters(in text: String) -> [Character: Int] {
      var resWithKey : Int
      var partResWithKey: Int
      var res: [Character: Int] = [:]
      var firstIndex = text.startIndex
      if text.count == 0 {
        return [:]
      }
      if text.count == 1 {
        res[text[firstIndex]] = 1
        return res
      } else if text.count > 1 {
        var result: [Character: Int] = [:]
        var partialResult: [Character: Int] = [:]
        var char = text[text.index(text.startIndex, offsetBy: 0)]
        for char2 in text.dropFirst() {
            if( char2 == char) {
                result[char2, default: 0] += 1
            }
        }
        partialResult = occurencesOfCharacters(in: String(text.dropFirst())) //
        // Append the two dictionaries together
        
        for( key, value) in partialResult {
            // Key has been found in the dictionary, remember the value\
            guard var resWithKey = result[key], let partResWithKey = partialResult[key] else {

                }
            resWithKey = resWithKey + partResWithKey
            
            }
        return resWithKey
        }
        
      }
      // <2>
let string: String = "Here is a string"
var result: [Character: Int] = [:]
result = occurencesOfCharacters(in: string)
for( key, val) in result {
    print("\n\(key),\(val)")
}

```

This is my 2nd attempt at counting the items recursively, I think I got the right idea and I just haven't implemented correctly yet. For some reason it is impossible to return [Character:Int]. The value is out of scope and in the wrong format anyway.

---

<div class="post-metadata">

**Author:** ![Peter-Schorn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/peter-schorn/32/11183_2.png) [@Peter-Schorn](https://forums.swift.org/u/Peter-Schorn)\
**Post date:** [August 25, 2021, 3:40pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/2 "2021-08-25T15:40:34Z")

</div>

> [@hairyyak](#):
>
> For some reason it is impossible to return `[Character: Int]`.

No, it's impossible to return anything _other_ than `[Character: Int]` because that's the declared return type of the function. You're trying to return an `Int`: `return resWithKey`. If you option-click on a variable in Xcode, it tells you the type.

---

<div class="post-metadata">

**Author:** ![hairyyak](https://avatars.discourse-cdn.com/v4/letter/h/bbce88/32.png) [@hairyyak](https://forums.swift.org/u/hairyyak)\
**Post date:** [August 25, 2021, 3:44pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/3 "2021-08-25T15:44:25Z")

</div>

But because of the way guard is arranged it is impossible to get a value of it.

---

<div class="post-metadata">

**Author:** ![Peter-Schorn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/peter-schorn/32/11183_2.png) [@Peter-Schorn](https://forums.swift.org/u/Peter-Schorn)\
**Post date:** [August 25, 2021, 3:45pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/4 "2021-08-25T15:45:59Z")

</div>

> [@hairyyak](#):
>
> But because of the way guard is arranged it is impossible to get a value of it.

I have absolutely no idea what you're referring to here.

> [@hairyyak](#):
>
> This is my 2nd attempt at counting the items recursively

This function should not be recursive. Here's the solution:

```swift
func occurrencesOfCharacters(in text: String) -> [Character: Int] {
    return text.reduce(into: [:]) { result, character in
        result[character, default: 0] += 1
    }
}

```

---

<div class="post-metadata">

**Author:** ![hairyyak](https://avatars.discourse-cdn.com/v4/letter/h/bbce88/32.png) [@hairyyak](https://forums.swift.org/u/hairyyak)\
**Post date:** [August 25, 2021, 3:56pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/5 "2021-08-25T15:56:54Z")

</div>

Cheers, that's great, thanks very much.

---

<div class="post-metadata">

**Author:** ![hairyyak](https://avatars.discourse-cdn.com/v4/letter/h/bbce88/32.png) [@hairyyak](https://forums.swift.org/u/hairyyak)\
**Post date:** [August 26, 2021, 12:10pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/6 "2021-08-26T12:10:43Z")

</div>

Just to demonstrate that it can be done here is the function using recursion:

```swift
func occurencesOfCharacters(in text: String, arrayCount: inout [Character: Int]) -> [Character: Int] {
      var resWithKey : Int
      var partResWithKey: Int
      var res: [Character: Int] = [:]
      var firstIndex = text.startIndex
      if text.count == 0 {
        return [:]
      }
      if text.count == 1 {
        res[text[firstIndex]] = 1
        return res
      } else if text.count > 1 {
        let char = text[firstIndex]
        arrayCount[char, default: 0] += 1
        var partialResult: [Character: Int] = [:]
        partialResult = occurencesOfCharacters(in: String(text.dropFirst()), arrayCount: &arrayCount)
        return arrayCount
        
      }
    return res
}
let string: String = "Here is a string"
var result: [Character: Int] = [:]
    result = occurencesOfCharacters(in: string, arrayCount: &result)
for( key, val) in result {
    print("\n\(key),\(val)")
}

```

---

<div class="post-metadata">

**Author:** ![Peter-Schorn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/peter-schorn/32/11183_2.png) [@Peter-Schorn](https://forums.swift.org/u/Peter-Schorn)\
**Post date:** [August 26, 2021, 7:07pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/7 "2021-08-26T19:07:00Z")

</div>

No this function doesn't work. It doesn't count the `g` in the string `Here is a string`. Even if you want to write a recursive function, there's a much simpler way to do it. Your version contains many unused variables and variables that are never mutated which should be changed to `let` constants.

```swift
func occurrencesOfCharacters<S: StringProtocol>(in string: S) -> [Character: Int] {
    
    if string.isEmpty {
        return [:]
    }

    var partialResult = occurrencesOfCharacters(
        in: string.dropFirst()
    )
    
    partialResult[string.first!, default: 0] += 1
    
    return partialResult
        
}

```

---

<div class="post-metadata">

**Author:** ![YOCKOW](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/yockow/32/20636_2.png) [@YOCKOW](https://forums.swift.org/u/YOCKOW)\
**Post date:** [August 27, 2021, 7:56am UTC](https://forums.swift.org/t/character-count-function-recursively/51488/9 "2021-08-27T07:56:36Z")

</div>

Sorry for bikeshedding 🤓

For performance reasons, it's better to use generics:  
`func occurrencesOfCharacters<S>(in string: S) -> [Character: Int] where S: StringProtocol`

When you call it recursively...  
`var partialResult = occurrencesOfCharacters(in: string.dropFirst())`

---

<div class="post-metadata">

**Author:** ![hairyyak](https://avatars.discourse-cdn.com/v4/letter/h/bbce88/32.png) [@hairyyak](https://forums.swift.org/u/hairyyak)\
**Post date:** [August 31, 2021, 2:23pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/10 "2021-08-31T14:23:08Z")

</div>

Not taking no for an answer it now counts the g and an empty string.

Here is the code:

```swift
func occurencesOfCharacters(in text: String, arrayCount: inout [Character: Int]) -> [Character: Int] {
      var resWithKey : Int
      var partResWithKey: Int
      var res: [Character: Int] = [:]
      var firstIndex = text.startIndex
      if text.count == 0 {
        arrayCount = [:]
        return res
      }
      if text.count == 1 {
        arrayCount[text[firstIndex]] = 1
        return res
      } else if text.count > 1 {
        let char = text[firstIndex]
        arrayCount[char, default: 0] += 1
        var partialResult: [Character: Int] = [:]
        partialResult = occurencesOfCharacters(in: String(text.dropFirst()), arrayCount: &arrayCount)
        return arrayCount
        
      }
    return res
}

```

---

<div class="post-metadata">

**Author:** ![Peter-Schorn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/peter-schorn/32/11183_2.png) [@Peter-Schorn](https://forums.swift.org/u/Peter-Schorn)\
**Post date:** [August 31, 2021, 5:04pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/11 "2021-08-31T17:04:09Z")

</div>

It still doesn't work. It gives the wrong result for `abbccc`.

> [@hairyyak](#):
>
> Not taking no for an answer

I don't know what answer you're referring to. I already demonstrated that it is possible to implement this function using recursion.

Still, your function contains unused variables: `resWithKey` and `partResWithKey`. The `res` and `firstIndex` variables were never mutated, so they should be `let` constants. Pay attention to the warnings in Xcode:

 ![Screen Shot 2021-08-31 at 12.03.55 PM](https://global.discourse-cdn.com/swift/original/3X/b/e/be78c1cec9e133801ffdaa960642ad43d5ff9d00.png)

---

<div class="post-metadata">

**Author:** ![ahti](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ahti/32/604_2.png) [@ahti](https://forums.swift.org/u/ahti)\
**Post date:** [September 1, 2021, 5:08pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/12 "2021-09-01T17:08:46Z")

</div>

> [@hairyyak](#):
>
> Not taking no for an answer

Also keep in mind that IIRC Swift does not guarantee tail call optimzation (and I'm not sure it would apply to your implementation if it did), so a recursive implementation will inevitably exhaust available stack space and crash for longer strings.

This is fine for a toy implementation to explore recursive patterns of course, but a limitation that should be kept in mind any time recursion is considered.

---

<div class="post-metadata">

**Author:** ![hairyyak](https://avatars.discourse-cdn.com/v4/letter/h/bbce88/32.png) [@hairyyak](https://forums.swift.org/u/hairyyak)\
**Post date:** [October 25, 2021, 12:54pm UTC](https://forums.swift.org/t/character-count-function-recursively/51488/13 "2021-10-25T12:54:47Z")

</div>

Sorry I didn't meant to start an argument. I just love recursion.
