Robert Robert - 7 months ago 26
Swift Question

How can I be sure calling `String.Index.advancedBy` won't cause a crash?

Calling

advancedBy
on a
String.CharacterView.Index
will cause an
EXC_BAD_ACCESS
if the distance to advance by is too large. This can be seen here:

let inputString = "Hello, world!"
let index = inputString.startIndex
let distance = 100
let newIndex = index.advancedBy(distance) // fatal error: cannot increment endIndex


Now, what if
index
had already been advanced from the string's
startIndex
some unknown number of times, and
distance
was some unsafe user input? How can I verify advancing the index by the given distance won't cause a crash?

Answer

You can use method advancedBy(n: Self.Distance, limit: Self) and set inputString endIndex as the limit:

let newIndex = index.advancedBy(distance, limit: inputString.endIndex)