Swift String insert()

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

Example

var greet = "Good Morning"

// insert ! to greet greet.insert("!", at: greet.endIndex)
print(greet) // Output: Good Morning!

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()

var distance = "X,Y"

// insert character at start and end index of distance distance.insert("(", at: distance.startIndex) distance.insert(")", at: distance.endIndex)
print(distance) // Output: (X,Y)

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,

var message = "Swift "

// use contentsOf property to insert multiple characters message.insert(contentsOf: "Programming", at: message.endIndex)
print(message) // Output: Swift Programming