I am trying to count the number of different Strings in an array. For example, my array is:
let stringArray = ["test", "test", "test1", "test2"]
The output should be "3" because "test" and "test" are the same, but "test", "test1", and "test2" are different. I am thinking about using a nested for loop to check the stringArray
string in the first loop against all of the other elements in stringArray
, but I can't quite get it to work. The only thing I can think of right now is to check on the inner loop if the strings are equal and break out -> go onto the next element. The problem I have is checking if the inner loop is on the last element. Here is what I have come up with:
var differentStrings = Int()
let stringArray = ["test", "test", "test1", "test2"]
for str in stringArray {
for str2 in stringArray {
if (str == str2) {
break
} else {
differentStrings = differentStrings + 1
}
}
}
print(differentStrings)
The output here is incorrect -> it prints out 5 because I am not checking in the else statement if str2
is the last element in the inner loop.
How do I get the number of different strings in an array?