The join
function takes an array of objects and joins them with a provided separator
. The following example presents a simple version of join
:
func join<Element: Equatable>(elements: [Element], separator: String) -> String { return elements.reduce("") { initial, element in let aSeparator = (element == elements.last) ? "" : separator return "\(initial)\(element)\(aSeparator)" } }
This function takes an array with a separator
, joins elements in an array, and provides a single String
. We can test it as follows:
let items = ["First", "Second", "Third"] let commaSeparatedItems = join(elements: items, separator: ", ")
The result will be "First, Second, Third"
.