Fatal error: cannot form a character from an empty string

So, I have a function that removes the trailing "," (comma + space) at the end of the line, and I get the above error, even if I guarantee that the line is not empty. The following code:

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

... displays the following console output:

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

The first instance is detail.remove(at: detail.endIndex)highlighted by the debugger, and although I can’t be sure that the space is present in the console message, I add a “,” at the end of each entry in the list, so any line that actually contains a comma should not only contain characters (as indicated by console), but at the end, two more characters must be added, which must be deleted.

Thanks in advance for any help for causing the error and how to solve it?

+4
2

import Foundation ( contains()) :

let details = ["one, two, three, ", "a, b", "once, twice, thrice, so nice, ", ""]

let filtered = details.map { (original: String) -> String in
  guard original.hasSuffix(", ") else { return original }
  return String(original.characters.dropLast(2))
}

print(filtered) // -> "["one, two, three", "a, b", "once, twice, thrice, so nice", ""]\n"

. , .

+2

detail.remove(at: detail.endIndex)

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

Source: https://habr.com/ru/post/1659564/


All Articles