Home
Swift
String Join, joined Examples
Updated Aug 23, 2023
Dot Net Perls
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: ",") print(result)
cat,dog,bird
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() print(result) // Display length of the result. print(result.endIndex)
ABCD Index(_rawBits: 262151)
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).
String Split
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 23, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen