Join. A string array contains many related strings. To combine these into a single string, we can use the joined() func. This is a simple and powerful func.
To join elements together, we use an instance method on the array. The argument is the delimiter string. An empty delimiter can be used.
First example. Here we join a 3-element string array on a comma char. The resulting string contains a comma in between the elements. No delimiter is at the start or the end.
Tip Joined() can handle more than one character in the delimiter. But each delimiter is the same.
// A string array of three elements.
let animals = ["cat", "dog", "bird"]
// Join the elements together with a comma delimiter.
let result = animals.joined(separator:",")
Empty delimiter. Sometimes we want to just combine (concatenate) all the strings together. No delimiter is required. We specify an empty string literal as the delimiter.
Tip This is much simpler than a loop and string concats. And on large collections it may have a performance advantage.
// A string array.
let values = ["A", "B", "C", "D"]
// Join the elements with an empty delimiter.
let result = values.joined()
// Display length of the result.
A note. This is an important aspect of joined: it adds no trailing delimiter. So we do not need special logic to remove a final characters.
Review. Joined is the opposite of split. These two methods can round-trip data. With components(), we split apart strings (this is the opposite of joined).