Convert Comma Separated String into Array in Swift

As you might have guessed from the topic, today we are going to convert a comma-separated string into an array in Swift. In the previous tutorial, we learned how to convert array to comma separated string in Swift.

Today we are going vice-a-versa of the above task.

Demonstration:

A string of subjects name separated by a comma- "Physics, Chemistry, Mathematics, English, Hindi"

The output should be an array of the above elements as ["Physics", "Chemistry", "Mathematics", "English", "Hindi"]

Let’s proceed toward the snippet part-

The first step is to create a string of the above-mentioned data as-

let subjectString="Physics, Chemistry, Mathematics, English, Hindi"

This is a string, now we need to convert it into an array, for this task we would now follow the below snippet-

let subjectArray=subjectString.components(separatedBy:",")

Here we have used subjectArray to store the substring, .components(separatedBy:) method is used which is used to convert a string into an array that required a separator(,).

As we have completed the given task we just need to print the array as-

print(subjectArray)

This would give us our expected output. The complete code is mentioned below-

let subjectString="Physics, Chemistry, Mathematics, English, Hindi"
let subjectArray=subjectString.components(separatedBy:",")
print(subjectArray)
Output:-
["Physics", " Chemistry", " Mathematics", " English", " Hindi"]

You can also use .split() instead of .components() it will function in the same way.

Leave a Reply

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