OneBite.Dev - Coding blog in a bite size

Split A String By Comma Sign In Swift

Code snippet for how to Split A String By Comma Sign In Swift with sample and detail explanation

In programming, often times you will be required to split a string by a specific character, such as a comma. In this article, we are going to focus on how to split a string by a comma sign in Swift.

Code snippet: Splitting a String by Comma

let text = "Apple, Banana, Orange"
let fruitArray = text.components(separatedBy: ", ")
for fruit in fruitArray {
    print(fruit)
}

Code Explanation: Splitting a String by Comma

In the above Swift code snippet, we start by declaring a string variable ‘text’ that consists of three different fruit names separated by a comma sign and a space.

let text = "Apple, Banana, Orange"

Next, we create an array ‘fruitArray’ by using the ‘components(separatedBy: ”, ”)’ method which splits the ‘text’ string at each instance of a comma and space, putting the separate parts into the array.

let fruitArray = text.components(separatedBy: ", ")

Finally, we execute a ‘for-in’ loop to iterate through the ‘fruitArray’. For each iteration, the loop will print out the current ‘fruit’ in the array.

for fruit in fruitArray {
    print(fruit)
}

This will output:

Apple
Banana
Orange

With these few lines of code, we’ve successfully split a string by a comma sign in Swift! Feel free to use and adapt this code for your own needs, whether it’s to organize lists of information or otherwise.

swift