Swift String dropFirst()

The dropFirst() method removes the first character of the string.

Example

var str = "Learn swift"

// remove first character from str print(str.dropFirst())
// Output: earn swift

dropFirst() Syntax

The syntax of the string dropFirst() method is:

string.dropFirst(i: Int)

Here, string is an object of the String class.


dropFirst() Parameter

The dropFirst() method can take a single parameter:

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

dropFirst() Return Value

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

Example 1: Swift String dropFirst()

var str = "Hello World"

// remove first character "H" from str print(str.dropFirst()) // ello World
var str1 = " Hello World"
// remove whitespace at the beginning of str1 print(str1.dropFirst()) // Hello World

Output

ello World
Hello World

In the above example, since str1 starts with whitespace, str1.dropFirst() removes the whitespace from the beginning of str1.


Example 2: Drop Multiple Number of Characters

var str = "Hello World"
print(str.dropFirst(6))
var str1 = "Learn Swift"
print(str1.dropFirst(7))

Output

World
wift

Here,

  • str.dropFirst(6) - removes the first 6 characters from str
  • str1.dropFirst(7) - removes the first 7 characters from str1