Reputation: 19
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
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
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