Add a string to another string in iOS using Swift


In this tutorial, I will let you know how you can add a string value to another string in iOS with Swift programming language.

Using the append() method to append a string

The Swift append() method is an in-built method that comes with the language.

Below is given the syntax for the Swift append() method:

string.append(str: String)

Now let’s see the example of adding a string to another using this method:

var str1 = "Swift"
var str2 = "Speedy"

str1.append(str2)

print(str1)

Output:

SwiftSpeedy

As you can see in the example, we have taken two strings str1 and str2. Then we are using the append() method to append the string str2 to str1.

Using the addition operator to add a string to another

Note that, using the append() method changes the original string as you can see in our previous example. To prevent this we can simply use the addition operator (+) as you can see below:

var str1 = "Swift"
var str2 = "Speedy"

var newStr = str1+str2
print(newStr)

Output:

SwiftSpeedy

Now you can see that, both the str1 is unchanged and created a new string newStr that contains str2.