Swift String insert()

The insert() method inserts a new character value into the string.

Example


insert() Syntax

The syntax of the string insert() method is:

string.insert(char: Character, at: string.index)

Here, string is an object of the String class.


insert() Parameters

The insert() method takes two parameters.

  • char - character to be inserted
  • at - insert char at the valid index of string

insert() Return Value

  • returns a string by inserting char to string.

Example 1: Swift string insert()

Here, we have inserted "(" and ")" at the starting and ending index of distance respectively.


Example 2: Add multiple Characters Using insert()

In Swift, we use contentsOf property to insert multiple characters to the string. For example,