Convert an array to comma separated string Swift

In this tutorial, you are going to learn how to convert an array to a comma-separated string in Swift.

Here we will create a string from an array that contains all the elements of the array and each one is separated by a comma.

For example, consider we have an array of string type as you can see below:

let fruitArray = ["Apple", "Mango", "Banana", "Orange"]

We have to create a string from the above array:

Apple, Mango, Banana, Orange

So let’s do it…

Below is our Swift program that shows you how to convert the array to a string with the items separated by comma:

let fruitArray = ["Apple", "Mango", "Banana", "Orange"]
let fruitString = fruitArray.joined(separator: ", ")


If we run the above code, we will see the output given below:

Apple, Mango, Banana, Orange

As you can see in the above code, we have an array with some elements. We have converted the array into a string using the array joined method with the separator , .

Notice that, we are using space after comma in the separator. This is because it is a grammatical rule in English. But if you don’t need it, you can only use comma (,) as a separator.

In the above example, we have the array of string type. But in the case of an array of integer type, it will not work. To convert an integer type array to a comma-separated string is a slightly tricky part in Swift. We have to use the array map() to do it with an array of int like you can see below:

let intArray = [11, 5, 8, 9]
let intString ={String($0)}.joined(separator: ", ")



11, 5, 8, 9

In the above code, we have converted each array item to a string using array map() method and then apply the joined() method.