Remove the last character of a string in Swift


If you want to remove the last character from a Swift string then you can do it easily using the removeLast() or the dropLast() method.

Both of the methods are able to perform the task. But there is a difference.

The removeLast() method is mutable. So it will modify the original string.

On the other hand, the dropLast() method is immutable. That means it will not modify the original string, but it will create a new string with the last character removed.

Now let’s see an example of removing the last character from the string using the removeLast() method:

var myName = "Abraham"

myName.removeLast()

print(myName)

Output:

Abraha

In the above example, the string myName has been modified because we have used the removeLast() method.

Now let’s do this thing using the dropLast() method:

var myName = "Abraham"

var removedLast = myName.dropLast()

print(removedLast)

Output:

Abraha

This time we have got a new array because we have used the dropLast() method.