How to Remove the Last Character of a Swift String

How to Remove the Last Character of a Swift String

Written by

in

Quick answer: Use String(str.dropLast()) to return a new string without the last character, or call _ = str.popLast() to remove the last character in place. Both methods safely handle empty strings without crashing and respect multi-byte Unicode characters like emojis.

Why this happens

If you come to Swift from another language—or encounter older Swift snippets online—you might try to slice off the final character using integer math like substringToIndex(countElements(expression) - 1) or substring(to:). In modern Swift, those APIs have been removed, and subscripting a String with an Int triggers compiler errors such as 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.

Swift forbids integer indexing on strings because a String is a BidirectionalCollection of extended grapheme clusters (Character), backed by variable-width UTF-8 storage. A single visible character—such as an accented letter or a family emoji—can occupy anywhere from one to dozens of bytes. Counting from the start of a string with integers would either require a slow linear scan every time or risk slicing a character in half.

Because String conforms to BidirectionalCollection and RangeReplaceableCollection, Swift provides built-in collection methods that step backward a single grapheme cluster from endIndex in constant time without manual index math.

How to fix it

1. Return a new string safely with dropLast() (Recommended)

When you do not want to mutate the original variable—or when you are working with a let constant—use dropLast(). It returns a Substring slice with the final character excluded, which you pass to String(_:) to produce an independent String.

let expression = "45+22"
let updated = String(expression.dropLast())
print(updated) // "45+2"

dropLast() is safe to call on empty strings. If expression is "", expression.dropLast() simply returns an empty Substring instead of crashing at runtime:

let empty = ""
let safeResult = String(empty.dropLast())
print(safeResult) // ""

You can also pass a count to dropLast(_:) to strip multiple trailing characters at once. If the count exceeds the string’s length, Swift clamps the result to an empty string:

let file = "report.csv"
let baseName = String(file.dropLast(4))
print(baseName) // "report"

Always wrap dropLast() in String(...) before storing the result in a struct property, class property, or array. A Substring keeps a reference to the entire backing memory buffer of the original String until all slices of it are deallocated.

2. Mutate a variable in place with popLast()

If your string is declared with var—for example, a calculator input buffer where tapping a Backspace button deletes the final character—mutating in place avoids allocating a new string buffer on every tap. Use popLast(), which removes and returns the last Character?.

var expression = "45+22"

if let removed = expression.popLast() {
    print("Removed: \(removed)") // "Removed: 2"
}
print(expression) // "45+2"

If you do not need the removed character, assign the return value to _ to silence the unused-result compiler warning:

var input = "A"
_ = input.popLast() // input is now ""
_ = input.popLast() // safely returns nil; input remains ""

Because popLast() returns nil when the string is empty, you can wire it directly to UI actions without extra bounds checks.

3. Mutate in place with removeLast() when non-empty is guaranteed

Swift also offers removeLast() and removeLast(_:), which mutate the string in place and replace verbose index manipulation like str.remove(at: str.index(before: str.endIndex)).

var greeting = "Hello!"
greeting.removeLast()
print(greeting) // "Hello"

Unlike popLast(), calling removeLast() on an empty string triggers an unrecoverable crash:

Fatal error: Can't remove last element from an empty collection

Similarly, calling removeLast(3) on a two-character string crashes at runtime. Only use removeLast() right after verifying the string is not empty:

var buffer = "45+"
if !buffer.isEmpty {
    buffer.removeLast()
}

For stripping multiple characters in place when you know the minimum length, validate count first or reassign using dropLast(_:):

var code = "ID-9821--"
code = String(code.dropLast(2)) // safe even if code has fewer than 2 characters

4. Strip a trailing character only when it matches

A common bug happens when developers call dropLast() unconditionally to clean up a trailing slash, comma, or newline, accidentally deleting valid characters when the delimiter is absent. Check hasSuffix(_:) before dropping:

func removingTrailingSlash(from path: String) -> String {
    guard path.hasSuffix("/") else { return path }
    return String(path.dropLast())
}

let urlA = removingTrailingSlash(from: "https://example.com/") // "https://example.com"
let urlB = removingTrailingSlash(from: "https://example.com")  // "https://example.com"

If the string might end with several repeated delimiters (such as "45+22,,,"), combine a while loop with last and popLast(), or use dropLast(while:):

let rawList = "apples,pears,,,"
let cleaned = String(rawList.dropLast(while: { $0 == "," }))
print(cleaned) // "apples,pears"

5. Update legacy substring and String.Index code

If you are maintaining older Swift code, you may run into deprecated or removed idioms that either fail to compile or crash on empty strings. Replace them with their modern equivalents:

var text = "Dolphin"

// Legacy (removed or deprecated—crashes if text is empty):
// let truncated = text.substring(to: text.index(before: text.endIndex))
// text.remove(at: text.index(before: text.endIndex))

// Modern non-mutating replacement:
let truncated = String(text.dropLast())

// Modern mutating replacement:
_ = text.popLast()

Avoid text.index(before: text.endIndex) unless you are building a custom Range<String.Index> for another API. Stepping backward from endIndex when startIndex == endIndex causes an immediate out-of-bounds trap.

How to prevent it

  • Default to dropLast() or popLast() over removeLast(). User input, network payloads, and localized strings can unexpectedly arrive empty; dropLast() and popLast() handle "" gracefully without runtime traps.
  • Convert Substring slices to String for long-term storage. Wrap dropLast() results in String(...) before saving them to properties so large parent strings can be freed from memory.
  • Verify delimiters with hasSuffix(_:) first. Never strip trailing punctuation blindly unless you are certain the character is present.
  • Do not bridge to NSString for character truncation. Calling (str as NSString).substring(to: nsStr.length - 1) counts 16-bit UTF-16 code units rather than visible characters, which splits multi-scalar emojis and flags into invalid surrogate halves.

FAQ

What is the difference between dropLast(), popLast(), and removeLast() in Swift?

dropLast() does not modify the original string and returns a Substring (returning empty if the string is already empty). popLast() mutates a var string in place and safely returns nil when empty, while removeLast() mutates in place and crashes with a fatal error if the string is empty.

Why does dropLast() return a Substring instead of a String?

Swift returns a Substring view that shares the original string’s memory buffer so chained slicing operations run fast without copying bytes at every step. Once you finish slicing, initialize a new String(substring) to copy only the remaining bytes into fresh storage.

Does dropLast() handle emojis and multi-byte Unicode characters properly?

Yes. Because Swift’s String collection elements are extended grapheme clusters (Character), dropLast() and popLast() remove an entire visible emoji—such as "👨‍👩‍👧‍👦" or "🇺🇸"—in a single call rather than stripping only its final Unicode scalar.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.