O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The join function

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".

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required