String concatenation involves combining 2 or more strings into a single string. This practical and straight-to-the-point will walk you through 5 different ways to concatenate strings in Swift (including mixing strings with variables). Without any further ado (like talking about the history of Swift), let’s get started.
Using the + operator
You can use the + operator to concatenate multiple strings, as shown below:
let s1 = "Welcome"
let s2 = "to"
let s3 = "Sling"
let s4 = "Academy."
let output = s1 + " " + s2 + " " + s3 + " " + s4
print(output)
Output:
Welcome to Sling Academy
Using string interpolation
String interpolation can be used to embed a string within another string. This is a way to embed expressions, including variables, within string literals.
Example:
let name = "Ranni The Witch"
let age = 1000
let location = "The Lands Between"
let message = "My name is \(name) and I am \(age) years old. I live in \(location)."
print(message)
Output:
My name is Ranni The Witch and I am 1000 years old. I live in The Lands Between.
We use string interpolation to embed the values of the name, age (an integer), and location variables within the string literal. The expression inside the parentheses, (name), (location), and (age), is replaced with the actual value of the variable at runtime.
Using the joined() method
The joined() method can be used to concatenate an array of strings into a single string. It takes a separator string as an argument, which is inserted between each string in the resulting concatenated string. Here’s the syntax:
array.joined(separator: String) -> String
Example:
let words = ["My", "name", "is", "Wolf"]
let sentence = words.joined(separator: " ")
print(sentence)
Output:
My name is Wolf
Using the += operator
You can use the += operator to append one string to another.
Example:
var str1 = "Hello"
let str2 = "World"
str1 += " " + str2
print(str1)
Output:
Hello World
Using the append() method
The append() method can be used to append one string to another.
Example:
var str1 = "Hello"
let str2 = "World"
str1.append(" ")
str1.append(str2)
print(str1)
Output:
Hello World
Above are some of the common ways to concatenate strings in Swift. Depending on the specific use case, one method may be preferred over the others.