Swift equivalent of Array.componentsJoinedByString?

SwiftXcode6

Swift Problem Overview


In Objective-C we can call componentsJoinedByString to produce a string with each element of the array separated by the supplied string. While Swift has a componentsSeparatedByString method on String, there doesn't appear to be the inverse of this on Array:

'Array<String>' does not have a member named 'componentsJoinedByString'

What is the inverse of componentsSeparatedByString in Swift?

Swift Solutions


Solution 1 - Swift

Swift 3.0:

Similar to Swift 2.0, but API renaming has renamed joinWithSeparator to joined(separator:).

let joinedString = ["1", "2", "3", "4", "5"].joined(separator: ", ")

// joinedString: String = "1, 2, 3, 4, 5" 

See Sequence.join(separator:) for more information.

Swift 2.0:

You can use the joinWithSeparator method on SequenceType to join an array of strings with a string separator.

let joinedString = ["1", "2", "3", "4", "5"].joinWithSeparator(", ")

// joinedString: String = "1, 2, 3, 4, 5" 

See SequenceType.joinWithSeparator(_:) for more information.

Swift 1.0:

You can use the join standard library function on String to join an array of strings with a string.

let joinedString = ", ".join(["1", "2", "3", "4", "5"])

// joinedString: String = "1, 2, 3, 4, 5" 

Or if you'd rather, you can use the global standard library function:

let joinedString = join(", ", ["1", "2", "3", "4", "5"])

// joinedString: String = "1, 2, 3, 4, 5"

Solution 2 - Swift

The componentsJoinedByString is still available on NSArray, but not on Swift Arrays. You can bridge back and forth though.

var nsarr = ["a", "b", "c"] as NSArray
var str = nsarr.componentsJoinedByString(",")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondevios1View Question on Stackoverflow
Solution 1 - SwiftJack LawrenceView Answer on Stackoverflow
Solution 2 - SwiftConnorView Answer on Stackoverflow