Remove last character from string. Swift language

Swift 4.0 (also Swift 5.0)

var str = "Hello, World"                           // "Hello, World"
str.dropLast()                                     // "Hello, Worl" (non-modifying)
str                                                // "Hello, World"
String(str.dropLast())                             // "Hello, Worl"

str.remove(at: str.index(before: str.endIndex))    // "d"
str                                                // "Hello, Worl" (modifying)

Swift 3.0

The APIs have gotten a bit more swifty, and as a result the Foundation extension has changed a bit:

var name: String = "Dolphin"
var truncated = name.substring(to: name.index(before: name.endIndex))
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Or the in-place version:

var name: String = "Dolphin"
name.remove(at: name.index(before: name.endIndex))
print(name)      // "Dolphi"

Thanks Zmey, Rob Allen!

Swift 2.0+ Way

There are a few ways to accomplish this:

Via the Foundation extension, despite not being part of the Swift library:

var name: String = "Dolphin"
var truncated = name.substringToIndex(name.endIndex.predecessor())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Using the removeRange() method (which alters the name):

var name: String = "Dolphin"    
name.removeAtIndex(name.endIndex.predecessor())
print(name) // "Dolphi"

Using the dropLast() function:

var name: String = "Dolphin"
var truncated = String(name.characters.dropLast())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

Old String.Index (Xcode 6 Beta 4 +) Way

Since String types in Swift aim to provide excellent UTF-8 support, you can no longer access character indexes/ranges/substrings using Int types. Instead, you use String.Index:

let name: String = "Dolphin"
let stringLength = count(name) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - 1
name.substringToIndex(advance(name.startIndex, substringIndex)) // "Dolphi"

Alternatively (for a more practical, but less educational example) you can use endIndex:

let name: String = "Dolphin"
name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"

Note: I found this to be a great starting point for understanding String.Index

Old (pre-Beta 4) Way

You can simply use the substringToIndex() function, providing it one less than the length of the String:

let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"

Leave a Comment