How to concatenate strings in Swift

In this tutorial, we will learn how to concatenate strings in Swift. We can concatenate or merge two or multiple strings in Swift easily with the following methods.

I have worked in various programming languages and I found concatenation of strings in Swift is the easiest.

print("hello"+"world")

The output will be:

helloworld

Quite easy right?

So with the + sign, we can concatenate the string.

Now we will be doing the same with string variables:

var firstString = "Hey this is nice,"
var secondString = "Hee hee It was a joke"
print(firstString+secondString)

Output:

Hey this is nice,Hee hee It was a joke
var firstString = "Hey this is nice,"
var secondString = "Hee hee It was a joke"
var finalString = firstString+secondString
print(finalString)

Output:

Hey this is nice,Hee hee It was a joke

We can also do this if we wish:

print(firstString + "" + secondString)

So, here we have seen that we can insert any string in between these two strings.

Concatenate a string variable with a string or text

var firstString = "Hey this is nice,"
print(firstString + "No I am going to print string directly like this")

Output:

Hey this is nice,No I am going to print string directly like this

Till now we have seen using var instead of let. But you could do the same using let. I hope you already know that the value of var can be modified in the future but if we use let we can’t do that.

Look closer at the below code snippet.

var myString = "Hey this is nice,"
myString += myString
print(myString)

Output:

Hey this is nice,Hey this is nice,

We can only do the above with var.

Concatenate a string variable into another string in Swift – Interpolation

This is actually called string interpolation.

Now we will be adding a string variable into another quoted string.

var myString = "Hey this is nice"
print("I will add the string variable value here \(myString) How was that?")

Output:

I will add the string variable value here Hey this is nice How was that?

There might be other possible ways to join strings but these were the easiest way.

 

Leave a Reply

Your email address will not be published. Required fields are marked *