I wrote this function, which (shall) count all occurrences of a specified character within a given string.
func countOccurrence(of char: Character, within str: String) -> Int {
var strCopy = str
var indexes = [String.Index]()
while true {
let curr = strCopy.firstIndex(of: char)
if let curr = curr {
indexes.append(curr)
let indexAfter = str.index(after: curr)
strCopy = String(strCopy[indexAfter..<strCopy.endIndex])
} else {
break
}
}
return indexes.count
}
let sTest = "Testing Swift, today Tuesday 123 ! tt".lowercased()
print(countOccurrence(of: "t", within: sTest)) // Result: 7
let sTest2 = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.".lowercased()
print(countOccurrence(of: "s", within: sTest2)) // Result: 4
Can I expect my function to work as expected or does someone see any flaws?
Can it become improved? Respectively, does someone know a better solution for the described task?
str.reduce(into:0){if $1=="t" {$0 += 1}}
\$\endgroup\$count(where:)
. Here is the related discussion on the Swift forums \$\endgroup\$