The dropLast()
method removes the last character of the string.
Example
var str = "Learn swift"
// remove last character from str
print(str.dropLast())
// Output: Learn swif
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()
var str = "Hello World"
// remove last character "d" from str
print(str.dropLast())
var str1 = "Hello World "
// remove whitespace at the end of str1
print(str1.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
var str = "Hello World"
print(str.dropLast(6))
var str1 = "Learn Swift"
print(str1.dropLast(7))
Output
Hello Lear
Here,
str.dropLast(6)
- removes the last 6 characters from strstr1.dropLast(7)
- removes the last 7 characters from str1