James Lingo James Lingo - 9 months ago 88
Swift Question

fatal error: Can't form a Character from an empty String

So I have function that strips off a trailing ", " (comma + space) at the end of a string and I'm getting the above error even though I'm ensuring that the string is not empty. The following code:

print("stripping trailing commas")
for var detail in details {
if detail.contains(",") {
detail.remove(at: detail.endIndex) // <-- Removes last space
detail.remove(at: detail.endIndex) // <-- Removes last comma

...results int the following console output:

stripping trailing commas
fatal error: Can't form a Character from an empty String

The first instance
detail.remove(at: detail.endIndex)
is being highlighted by the debugger, and while I can't be sure the space is present from the console message, I'm adding ", " at the end of each entry in a list so any string that actually contains a comma should not only have characters (as the console indicates) but it should have an extra two chars at the end that need to be stripped.

Thanks in advance, for any help on what's causing the error and how to resolve?

Answer Source

Try change

detail.remove(at: detail.endIndex)


detail.remove(at: detail.index(before: detail.endIndex))