VOOZH about

URL: https://www.geeksforgeeks.org/swift/how-to-concatenate-strings-in-swift/

⇱ How to Concatenate Strings in Swift? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Concatenate Strings in Swift?

Last Updated : 27 Jul, 2022

In Swift, a string is a sequence of a character for example "GeeksforGeeks", "I love GeeksforGeeks", etc, and represented by a String type. A string can be mutable and immutable. When a string is assigned to a variable, such kind of string is known as a mutable string(can be modified) whereas when a string is assigned to a constant, such kind of string is known as an immutable string(cannot be modified). In Swift, we are allowed to concatenate strings. String Concatenation is the technique of creating a new string by adding two strings. We can perform string concatenation using the following methods:

  • Using + operator
  • Using += operator
  • Using append() method

Now we will discuss all these methods in detail along with examples.

Using + operator

String concatenation using the + operator is the most common method of concatenation. The addition(+) operator creates a new string by adding two or more strings together. You can also use this method to concatenate multiline string literals. Let us discuss this with the help of the following example.

Syntax:

string1 + string2

Example:

Output:

String 1: Hello! Maya 
String 2: I am a food blogger 
Final String 1: Hello! Maya I am a food blogger 
Final String 2: Hello! Maya I am a food blogger I love eating food
Final String 3: Hello! Maya I live in Mumbai

Using += operator

In Swift, we can add and assign a string to the existing string variable using the addition assignment operator(+=). Let us discuss this concept with the help of the following example.

Syntax:

string1 += string2

Example:

Output:

Final String 1: Hello! Maya I am a food blogger 
Final String 2: I am a food blogger I love eating food

Using append() method

In Swift, we can also concatenate strings using the append() method. This method adds a new element at the end of the specified mutable string. It does not return any value it only updates the given string.

Syntax:

string1.append(string2)

Output:

Final String : Hello! Maya I am a food blogger 
Comment
Article Tags:

Explore