Search code examples
swiftstringcharacter

How to go through the elements of type string


I am writing a function that should return the number of duplicates. I can’t understand how to go through the elements of type string.

func countDuplicates(_ s:String) -> Int {
    var duplicates = 0

    for i in s {
        duplicates += 1
    }

    return duplicates
}

Solution

  • You can try:

    func countDuplicates(_ s:String) -> Int {
        return s.count - Set(s).count
    }
    

    Where:

    s.count // total number of characters
    Set(s).count // number of unique characters