Warpzit
Warpzit

Reputation: 28162

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.

Upvotes: 1

Views: 2314

Answers (2)

Martin R
Martin R

Reputation: 539795

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

let string = "a🇨🇷b😈"

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

Output:

b
🇨🇷
a

Upvotes: 7

TheValyreanGroup
TheValyreanGroup

Reputation: 3599

You can do something like your second one. After you enter the for, you can just get the index directly from the string. In Swift, a string is just an array of characters.

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

Upvotes: 1

Related Questions