Let's say I have a variable that contains a string var someString = "@@@@@@@@@@"
and I'd like to insert a "#" symbol for every 1-3 characters in the string, so basically I wanna create something like this: var someString = "@@#@#@@@#@#@@#@"
Ah yes. Can't rely on the index to still work after someString.insert:
Calling this method invalidates any existing indices for use with this string.
So the above code is prone to crash, even though it might not crash every time.
This one should be correct since it avoids mutating the string while iterating on it:
var slices: [Substring] = []
var beginIndex = someString.startIndex
var currentIndex = someString.startIndex
var counter: Int = .random(in: 0..<3)
while currentIndex != someString.endIndex {
if counter == 0 {
slices.append(someString[beginIndex..<currentIndex])
beginIndex = currentIndex // starting new slice at current index
counter = .random(in: 0..<3)
} else {
counter -= 1
}
someString.formIndex(after: ¤tIndex) // go to next character
}
slices.append(someString[beginIndex..<currentIndex])
someString = slices.joined(separator: "#")