count unique characters in a string in swift

main.swift
let str = "hello"
var dict = [Character: Int]()

for char in str {
    if let count = dict[char] {
        dict[char] = count + 1
    } else {
        dict[char] = 1
    }
}

print(dict) // Prints "["h": 1, "e": 1, "l": 2, "o": 1]"
print(dict.count) // Prints "4"
264 chars
14 lines

Explanation:

  • We start by initializing an empty dictionary dict which will store the counts of each unique character.
  • Then we loop through each character char in the input string str.
  • For each character, we check if it already exists in the dictionary using optional binding (if let).
  • If it does, we increment the count by 1. If it doesn't, we add a new key-value pair with the count as 1.
  • Finally, we print the dictionary and its count.

gistlibby LogSnag