To convert an array to string in Swift, call Array.joined() function.
For instance, let’s combine a list of names into a string that separates the names with a space:
let names = ["Alice", "Bob", "Charlie"] let nameString = names.joined(separator: " ") print(nameString)
Output:
Alice Bob Charlie
1. The Array.joined() Function in Swift
The Array.joined() function in Swift can be called to create a string based on the elements of the array.
The syntax is:
Array.joined(separator:)
Where the separator is an optional argument. If specified, it defines the separator to put between each element in the array in the resulting string.
For instance, let’s combine a list of names without a separator:
let names = ["Alice", "Bob", "Charlie"] let nameString = names.joined() print(nameString)
Output:
AliceBobCharlie
Now, let’s separate these names by a comma:
let names = ["Alice", "Bob", "Charlie"] let nameString = names.joined(separator: ",") print(nameString)
Output:
Alice,Bob,Charlie
Notice that the separator does not need to be a single character.
For example, let’s separate the names with three dashes:
let names = ["Alice", "Bob", "Charlie"] let nameString = names.joined(separator: "---") print(nameString)
Output:
Alice---Bob---Charlie
Now that you understand how the Array.joined() method works, let’s take a look at some common tasks you can solve using it.
2. How to Create a String from an Array of Characters
To create a string from a list of singular characters, use the Array.joined() function just like you would use it on an array of strings.
Let’s see examples of separating the characters by a comma and not separating the characters at all.
2.1. Separated by a Comma
let names = ["A", "B", "C"] let nameString = names.joined(separator: ",") print(nameString)
Output:
A,B,C
2.2. Non-separated
let names = ["A", "B", "C"] let nameString = names.joined() print(nameString)
Output:
ABC
3. How to Create a String from Numbers
If you have an array of numbers, you cannot directly call Array.joined() on it to create a string. Instead, you need to convert the array of numbers to an array of strings.
For example:
let nums = [1.0, 2.0, 3.0] let numsString = nums.map { String($0) }.joined(separator: ", ") print(numsString)
Output:
1.0, 2.0, 3.0
In case you are wondering what the $0 does, check out this article.
4. Conclusion
Today you learned how to use the Array.joined() function in Swift.
To recap, you can combine an array of strings to a string with the Array.joined() function. If you want to separate the strings, specify a separator in the call.
names.joined(separator: " ")
Thanks for reading.