Let's start with this string :
let abc : String = "aaaabbbbbbbccffffde"
And have the output in a new variable
var result = ""
Let's use an index to go through the characters in the string
var index = abc.startIndex
while index < abc.endIndex {
//There is already one character :
let char = abc[index]
var count = 0
//Let's check the following characters, if any
repeat {
count += 1
index = abc.index(after: index)
} while index < abc.endIndex && abc[index] == char
//and update the result accordingly
result += count < 3 ?
String(repeating: char, count: count) :
String(char) + String(count)
}
And here is the result :
print(result) //a4b7ccd3e