How to get # of distinct characters in a string? (Swift 4.2 + )

2.6k Views Asked by At

This algorithm or code should work for any # of unique character in a string, by the condition we use to check after.

For instance (If I have a string that I want to know if we have at least 7 unique characters we can do):

let number_of_distinct = Set(some_string.characters).count

if(number_of_distinct >= 7)
{
  // yes we have at least 7 unique chars.
}
else
{
  // no we don't have at least 7 unique chars.
}

However, this technique seems to be deprecated in Swift 4.2 +, due to the way Strings were updated in Swift 4.0 +.

What would be the new correct approach for this technique mentioned above?

2

There are 2 best solutions below

1
On BEST ANSWER

Just remove the .characters

let number_of_distinct = Set(some_string).count

if(number_of_distinct >= 7)
{
    print("yes")
    // yes we have at least 7 unique chars.
}
else
{
    print("no")
    // no we don't have at least 7 unique chars.
}
0
On

You can also do this without using the Set.

func printUniqueCompleteSubString(from string: String) {

    var uniquString = ""
    uniquString = string.reduce(uniquString) { (result, char) -> String in
        if result.contains(char) {
            return result
        }
        else {
            return result + String.init(char)
        }
    }

    print("Unique String is:", uniquString)

}