Convert array to comma separated string in Swift

This tutorial is based on the task to convert a given array into a comma separate string in Swift. For this, we need an array of a few elements which need to be converted into comma separated strings.

How to convert an array of strings to comma-separated string?

Sometimes we need to convert an array of strings into a comma-separated string, for this we need to create an array of strings in Swift as-

let Array = ["Codespeedy", "is" , "a", "programming", "blog","website"]

This is the format to create an array of strings, you can choose the elements of your choice or work with the array you have already created.

let ArrayString = Array.joined(separator: ", ")

print(ArrayString)

As you can see we have used joined with separator (,) to join the strings. This code will give us output as-

Output:
Codespeedy, is, a, programming, blog, website

But what if you want to convert an array of integers into comma-separated strings

How to convert an array of integers into comma-separated string?

The above method is not compatible with the array of integers we need to use array map() method and joined with separator (,) to get the task done.

Creating an array of integers-

let Array = [11,4,6,7]

We have successfully created an array with integer elements and now we are going to convert it into comma-separated string using-

let Array1 = Array.map{String($0)}.joined(separator: ", ")

print(Array1)
Output:
11,4,6,7

We have successfully converted an array of integers into a comma-separated string. Hence we have completed the task to convert an array into comma-separated string in Swift.

Leave a Reply

Your email address will not be published. Required fields are marked *