Rosalind Rosalind - 1 month ago 31
Swift Question

Startindex swift 3 issue

I get a startIndex error. The error is "Value of type 'string.index'(aka'string.characterview.index')has no member'advanced". Heres code and an image of the error.

return self.substring(with: (self.startIndex.advanced(by: fromInclusively)..<self.startIndex.advanced(by: toExclusively)))


Image of Error of startindex

Answer

In swift 3 you can no longer use advanced, successor or predecessor, instead you need to use

let indexAfter = someString.index(after: someIndex)
let indexBefore = someString.index(before: someIndex)
let anyOtherIndex = someString.index(someIndex, offsetBy: distance)

so your code should look like this

let index = (hasOverflow) ? 
text.index(text.startIndex, offsetBy: expectedInputLength) :
text.index(text.startIndex, offsetBy: text.characters.count)

As a side note,

text.index(text.startIndex, offsetBy: text.characters.count)

Is actually the same as

text.endIndex

So you can use this instead

let index = (hasOverflow) ? 
text.index(text.startIndex, offsetBy: expectedInputLength) :
text.endIndex
Comments