How to split a string into an array of strings in Swift

In order to split a given string into an array containing substrings from the original string, the components(separatedBy:) method can be used.

Given a string of items separated by spaces, here is how to get an array of components separated by space:

let str = "Foundation UIKit SwiftUI String Components”
let items = str.components(separatedBy: " “)

The items array now looks like this:

["Foundation", "UIKit", "SwiftUI", "String", "Components”]

Here is an example of splitting a string of items separated by commas:

let str = "Foundation,String,Components"
let items = str.components(separatedBy: ",")

How to split a string of items separated by multiple different characters? A CharacterSet comes in handy in that case and allows you to specify which characters are going to be used as separators. Take a look at an example where a comma, semicolon and a dash are used as separators:

let str = "Foundation,String;Components-Swift”

let separators = CharacterSet(charactersIn: ",;-")
let items = str.components(separatedBy: separators)

The items array looks like this:

["Foundation", "String", "Components", "Swift”]

Related tutorials: