OneBite.Dev - Coding blog in a bite size

Concatenate A String In Swift

Code snippet for how to Concatenate A String In Swift with sample and detail explanation

In this article, we are going to discuss a common programming task: concatenating or joining strings in Swift. By the end of this guide, you will understand not only how to carry out this operation, but also the concept underlining these functions.

Code snippet for Concatenating String in Swift

The basic code to concatenate two or more strings in swift is as follows:

var str1 = "Hello"
var str2 = ", World"
var str3 = str1 + str2
print(str3)

In this code snippet, “Hello” and ”, World” are concatenated to print “Hello, World”.

Code Explanation for Concatenating String in Swift

Let’s break down the code to understand how string concatenation happens in Swift.

  1. First, we declare a string variable str1 and initialize it with the value “Hello”.
var str1 = "Hello"
  1. In the next line, we declare another string variable str2 and initialize it with the value ”, World”.
var str2 = ", World"
  1. To concatenate str1 and str2, we simply use the + operator. So str1 + str2 will give us “Hello, World”. We save this concatenated string in a new variable str3.
var str3 = str1 + str2
  1. Finally, we print the str3 variable which contains the concatenated string.
print(str3)
  1. The output will be:
Hello, World

By using the + operator, Swift not only makes it easy to concatenate strings but also makes the code cleaner and easier to understand. Note that you can concatenate more than two strings, and the variables don’t need to be strings initially—they can be variables that are converted to strings.

swift