Swift – Split string by comma

To split a given string by comma separator in Swift, use String.split() function. Call split() function on the String and pass the comma character as value for separator parameter.

str.split(separator: Character(","))

split() function returns a String Array with the splits as elements.

Examples

ADVERTISEMENT

1. Split string by comma into array of strings

In this example, we will take a string in variable str where the values are separated by comma separator. We shall split this string into an array of values.

main.swift

let str = "apple,banana,cherry"
var result = str.split(separator: Character(","))
print(result)

Output

Conclusion

In this Swift Tutorial, we learned how to split a string by comma into array of values, using String.split() function.