R Moyer R Moyer - 1 year ago 90
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

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

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

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
and the
from within the loop has proven difficult.

Any suggestions or improvements on this function?

Answer Source

How about this:

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

print(s1) // prints "Do this thing"

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download