Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build CSV from Array of Strings in Swift in a single line of code

Tags:

ios

swift

I have an array of strings in swift and I thought I could do:

array.join(",") to return a comma separated list of the elements

The error I'm getting is: Array<String> not convertible to 'String'

How can I do this correctly in as little code as possible.

I can do it with a loop to build a string but I thought there was a simpler way to do this.

like image 673
Jeef Avatar asked Sep 10 '14 14:09

Jeef


3 Answers

Given an array of strings:

var x = ["one", "two", "three"]

the correct syntax to join strings is:

Swift 1.2

",".join(x)

Swift 2.0

x.joinWithSeparator(",")
like image 133
Antonio Avatar answered Nov 13 '22 13:11

Antonio


In Swift 2,

array.joinWithSeparator(",")
like image 8
Jeffrey Neo Avatar answered Nov 13 '22 13:11

Jeffrey Neo


In Swift 4

let array:[String] = ["one", "two","three"]

array.joined(separator: " ")
like image 5
Anushk Avatar answered Nov 13 '22 12:11

Anushk