How to Split a String by separator into An array in swift with example

This article explains about multiple ways to split a string into array in swift 2,3 and 4 with examples

How to Split the string by spaces in Swift?

There are multiple ways we can do

In the Swift 2 version, You can use the componentsSeparatedByString of a string. It returns an array of substrings.

import Foundation

var name: String = "Hello Welcome to cb "
let substrings = name.componentsSeparatedByString(" ")
print(substrings[0]);
print(substrings[1]);
print(substrings[2]);

In The Swift 3 version,

You can use the String components method which accepts separatedBy parameters with blank space.

components return the array of substring split by space.

You can access array elements using the index mechanism

import Foundation

var name: String = "first middle last"
let nameArray = name.components(separatedBy: " ")

var firstName: String = nameArray[0]
var middleName: String = nameArray[1]
var lastName: String = nameArray[2]
print(firstName);  //first
print(middleName); //middle
print(lastName); //last

In The Swift 4 version, You can use the split method of a String.

import Foundation

var name: String = "Hello Welcome to cb "
let substrings = name.split(separator: " ")
print(substrings)

Output:

["Hello", "Welcome", "to", "cb"]

Conclusion

You can also split with any characters using the above methods based on the Swift version.