Comment by saagarjha

4 years ago

The index is not bogus, the API is working as designed. The example provided shows the use of the index, which I understand can be confusing because the index returned may not always be valid for this, but the index is decidedly valid. FWIW, since String is a BiderectionalCollection, this code works for what you are probably trying to do:

  let s = "Swift"
  if !s.isEmpty,
      let index = s.index(s.startIndex, offsetBy: 5, limitedBy: s.index(before: s.endIndex)) {
    print(s[index])
  }

I am sure the equivalent code in other languages, barring Python, is going to be similarly verbose.