join an array of substrings into a string in swift

To join an array of substrings into a string in Swift, you can use the joined() method provided by the Sequence protocol. Here's an example:

main.swift
let substrings = ["Hello", "world", "!"]
let concatenatedString = substrings.joined(separator: " ")
print(concatenatedString) // Output: "Hello world !"
153 chars
4 lines

In this example, we first create an array of substrings using square brackets notation. Then, we call the joined() method on the array and pass in the desired separator as a parameter. Finally, we print out the resulting concatenated string.

Alternatively, you could also use the joined(separator:) method provided by the Collection protocol:

main.swift
let concatenatedString = substrings.joined(separator: " ")
59 chars
2 lines

This works in the same way as the first example, but the method is called directly on the array instead of using the Sequence protocol.

Either way, both joined() and joined(separator:) can be used to easily concatenate an array of substrings into a single string in Swift.

gistlibby LogSnag