R Moyer R Moyer - 1 month ago 19
Swift Question

Iterating and Manipulating Strings in Swift 3

What I'm trying to do should be simple, but I can only come up with verbose solutions thanks to Swifts handling of string indices and characters. Basically I have a large list of instructions, stored as an array of strings. Example values are:

"1) Do this thing"
"2) Do that thing"


I want to remove the numbering (e.g.
"1) "
) from these strings so that I can create my own formatting later when I add the strings to a
UITextView
.

I have been able to get the following code to work:

func removeNumbering(from instruction: inout String) {
var indexOfFirstLetter = 0

for (index, character) in instruction.unicodeScalars.enumerated() {
if NSCharacterSet.letters.contains(character) {
indexOfFirstLetter = index
break
}
}

let range = instruction.startIndex ..< instruction.index(instruction.startIndex, offsetBy: indexOfFirstLetter)
instruction.removeSubrange(range)
}


Is there a more concise way to do this? Seems like I should be able to remove characters until the loop finds the first letter, but getting access to both the
unicodeScalar
and the
String.Index
from within the loop has proven difficult.

Any suggestions or improvements on this function?

Answer

How about this:

var s1 = "1) Do this thing"
var s2 = "2) Do that thing"

s1.characters.removeFirst(3)
print(s1) // prints "Do this thing"

s2.characters.removeFirst(3)
print(s2) // prints "Do this thing"

If you need more elaborate trimming, use regular expression:

s1.replacingOccurrences(of: "[0-9]\\) ", with: "", options: .regularExpression)
print(s1) // prints "Do this thing"