Split a string into an array of substrings in Swift


In this Swift tutorial, you are going to learn how to split a string into an array of substrings with the help of examples.

To achieve this task, we will use the Swift split() method. This is an in-built method that can help us break a string into multiple parts at specified separators and returns an array. Each element of the array will be the substrings.

Swift program for splitting a string

Below is our given Swift program that splits a string into multiple parts:

var text = "SwiftSpeedy is an amazing programming language for iOS development"
var splittedText = text.split(separator: " ")
print(splittedText)

Output:

["SwiftSpeedy", "is", "an", "amazing", "programming", "language", "for", "iOS", "development"]

In the above program, we are using whitespace to separate our string into multiple parts. After we run our program, we got an array of substrings.

Below is another example, where we are splitting our string with hyphen (-) seperator:

var text = "Best-of-luck"
var splittedText = text.split(separator: "-")
print(splittedText)

Output:

[“Best”, “of”, “luck”]

As you can see above, this time our program returns an array from the string that split at the - specifier.

Split a string with limit

It is also possible to split a string with a limit. Below is how we can do it:

var myText = "You-can-easily-learn-Swift"
var splittedText = myText.split(separator: "-", maxSplits: 2)
print(splittedText)

Output:

[“You”, “can”, “easily-learn-Swift”]

In the above example, you can see that we have set a limit 2. So we go the array up to the index number 2. The index number starts with 0.