Convert comma-separated string to array in Swift


In this tutorial, you are going to learn something that may be helpful in your iOS development.

From the title, you have already known that we are going to convert a comma-separated string into an array using the Swift components(separatedBy:) method. Each item separated by the comma is going to be the element of the array.

So let’s see the code that will do the task:

let colorString = "Green, White, Blue, Yellow"
let colorArray = colorString.components(separatedBy: ", ")
print(colorArray)

Output

["Green", "White", "Blue", "Yellow"]

We did it…

In the above program, we have created a string colorString and then apply the components(separatedBy:)method to get the substring.

As you can see in the program, the string contains some colors separated by a comma:

"Green, White, Blue, Yellow".

You have to separate each color and make them elements of an array. In simple words, you have to create a substring from the string and convert it into a Swift array.

So what is the functionality of the components(separatedBy:)method?

Well, this method is used to divide a Swift string into substrings using the specified string separator. Each of the substrings becomes the element of the array.

Below is the syntax of the method:

string.components(separated: separator)

Where separator is the parameter that we have to provide. The separator parameter is to used to specify the separator to be used to separate the string into parts. In our example, the separator is “, “as you can see below:

let colorArray = colorString.components(separatedBy: ", ")

I hope this tutorial becomes helpful in your iOS app development project or in any other Apple development project.