Jaya chandra
Jaya chandra

Reputation: 19

M getting fatal error: cannot decrement before startIndex.please resolve

Getting an fatal error when I'm trying execute the following code:

 let truncated = "{" + stringToSend.substring(to: stringToSend.characters.index(before: stringToSend.endIndex)) + "}"
                //stringToSend = "tttttttttttttttttttttttttttttttttttttttttt" + truncated + "@"

Upvotes: 0

Views: 679

Answers (2)

André
André

Reputation: 326

Your error occurs because your string is empty or has only one character.

A simple if can fix it.

Swift 3

if stringToSend.count > 1{
   let truncated = stringToSend.substring(to: stringToSend.characters.index(before: stringToSend.endIndex))
}

Swift 4:

if stringToSend.count > 1{
   let truncated = String(stringToSend[stringToSend.startIndex...stringToSend.index(before: stringToSend.endIndex)])
}

Upvotes: 1

vadian
vadian

Reputation: 285290

This error occurs if stringToSend is empty.

The code gets the index before the endIndex. If the string is empty the index before the endIndex is before startIndex which raises an exception.

Solution: Make sure that stringToSend is not empty

Upvotes: 0

Related Questions