This tutorial is going to let you know everything about the Swift string insert() method with the help of easy-to-understand examples.
insert() method can insert a new character in a specified position of a string.
Below is an example of using the
insert() method to insert a character at the end of a string:
var sendMessage = "Hello World" sendMessage.insert("!", at: sendMessage.endIndex) print(sendMessage)
Below is given the syntax for the insert() method:
string.insert(character, at: INDEX_POSITION)
In the above syntax, you can see that the method is accepting two parameters.
string is a string,
character is the character to be inserted in our string.
INDEX_POSITION is the position where we want to insert our string.
Below is an example of a Swift program to insert a character to a specific position of a string by providing the index number using the
var myString = "SwiftSpeedy" // Character to be inserted in our string var ch :Character = "X" // Index number of a position var i = myString.index(myString.startIndex, offsetBy: 5) // Insert the character to the specified position myString.insert(ch, at: i) print( myString )
Now see the example below where we are inserting a character at the first position and adding another character at the end position of our string:
var site = "swiftspeedy.com" site.insert("[", at: site.startIndex) site.insert("]", at: site.endIndex) print(site)
In the above example, we have inserted the character
[ at the starting index and inserted the
] character in the ending index of the string.
startIndex property can get the index of starting position and the
endIndex property can get the index of the end position. So we used these properties to insert our character to the starting and ending of our string.
contentsOf property with the
index() method, we can easily insert multiple characters to a Swift string at a specific position. Below is an example to perform it:
var siteName = "Swift" // Using the contentsOf property to insert multiple characters siteName.insert(contentsOf: "Speedy", at: siteName.endIndex) print(siteName)
In the above example, we have used the
endIndex property to insert multiple characters to the ending of our string. With this same procedure, you can insert at the starting position by using the
If you want, you can also add multiple characters anywhere by providing the index number like you can see in the example below:
var siteName = "Swift" var i = siteName.index(siteName.startIndex, offsetBy: 2) // Using the contentsOf property to insert multiple characters siteName.insert(contentsOf: "Speedy", at: i) print(siteName)