Warpzit Warpzit - 2 days ago 5
Swift Question

Iterate over part of String in Swift

Why in the world are Swift String operations so complex and tiresome to work with?

I have to iterate over a String in reverse but ignoring the first char. Now this could be done like following:

var firstTime = true
for i in textBefore.characters.reversed() {
if firstTime {
firstTime = false
} else {
if String(i).personalFunction() {
// something
} else {
// something else
}
}
}


But really I just want to do something like:

textBefore = textBefore.characters.reversed()
for i in 1...textBefore.characters.count {
if textBefore.get(i).personalFunction() {
// something
} else {
// something else
}
}


So why can't we get index as int. And why is textBefore.characters.reversed() not a String or simply have String have a reverse function. All these issues just makes it so frustrating to work with Strings in Swift and makes us do stupid stuff as converting a String to an array of chars :S or stuff like my proposed solution above... Also we can't make for loops in the old fashion... I simply need some Swift guru to point my brain in the right direction for this stuff.

Answer

string.characters is a collection of characters. Use reversed() to access the remaining elements in reverse order, anddropFirst() to skip the initial element of the reverse collection:

let string = "abc"

for ch in string.characters.reversed().dropFirst() {
    print(ch)
    // `ch` is a Character. Use `String(ch)` if you need a String.
}

// Output: b, a
Comments