Mercutio
Mercutio

Reputation: 1296

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(",") {
print(detail)
                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
2016, 
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?

Upvotes: 6

Views: 5233

Answers (2)

user887210
user887210

Reputation:

A simple way to do this without using import Foundation (needed for contains()) or calculating indexes would be something like this:

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"

This won't remove any empty strings that are in the returned array. If you need that functionality it can easily be added.

Upvotes: 2

Joe Smith
Joe Smith

Reputation: 1920

Try change

detail.remove(at: detail.endIndex)

to

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

Upvotes: 10

Related Questions