Swift String dropLast()

The dropLast() method removes the last character of the string.

Example


dropLast() Syntax

The syntax of the string dropLast() method is:

string.dropLast(i: Int)

Here, string is an object of the String class.


dropLast() Parameter

The dropLast() method can take a single parameter:

  • i (optional) - number of characters to be dropped from the end of the string

dropLast() Return Value

  • returns a substring after removing the specified number of characters from the end of the string.

Example 1: Swift String dropLast()

Output

Hello Worl
Hello World

In the above example, since str1 ends with whitespace, str1.dropLast() removes the whitespace from the end of str1.


Example 2: Drop Multiple Number of Characters

Output

Hello
Lear

Here,

  • str.dropLast(6) - removes the last 6 characters from str
  • str1.dropLast(7) - removes the last 7 characters from str1