Skip to content
DeveloperMemos

Splitting a String into an Array in Swift

Swift, String Manipulation, Arrays1 min read

Splitting strings into arrays is a common task in Swift programming. This guide covers various methods to achieve this, tailored to different requirements.

Basic String Splitting

Using components(separatedBy:)

The components(separatedBy:) method is part of the Foundation framework. It splits a string into an array of substrings based on a separator.

1import Foundation
2
3let sentence = "Hello, World"
4let words = sentence.components(separatedBy: ", ")
5// words = ["Hello", "World"]

Using split(separator:)

The split(separator:) method is a Swift native way to split strings. It returns a Substring array.

1let sentence = "Hello, World"
2let words = sentence.split(separator: ",")
3// words = ["Hello", " World"]

Handling Multiple Separators

If you need to split a string using multiple separators, you can use components(separatedBy:) with a character set.

1import Foundation
2
3let data = "apple,orange;banana"
4let separators = CharacterSet(charactersIn: ",;")
5let fruits = data.components(separatedBy: separators)
6// fruits = ["apple", "orange", "banana"]

Preserving Empty Subsequences

By default, split(separator:) omits empty subsequences. To include them, set omittingEmptySubsequences to false.

1let data = "a,,b,c"
2let parts = data.split(separator: ",", omittingEmptySubsequences: false)
3// parts = ["a", "", "b", "c"]

Splitting with a Closure

For more complex splitting logic, use split with a closure.

1let data = "123-456-789"
2let parts = data.split { $0 == "-" }
3// parts = ["123", "456", "789"]

In Closing

Swift provides multiple ways to split strings into arrays, catering to different needs. Whether you need a simple split by a single character, handling multiple separators, or complex conditions, Swift's string manipulation capabilities have you covered.