Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift String dropLast()
In this tutorial, we will learn about the Swift string dropLast() method with the help of examples.
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
Did you find this article helpful?