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.
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.
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
Sometimes we want to just combine (concatenate) all the strings together. No delimiter is required. We specify an empty string
literal as the delimiter.
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)
This is an important aspect of joined: it adds no trailing delimiter. So we do not need special logic to remove a final characters.
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).