components(separatedBy:) method. To split a string by any sequence of whitespace, use split(separator:whereSeparator:) or components(separatedBy: .whitespaces). Always handle the optional nature of the resulting array elements.Understanding String Splitting in Swift
String manipulation is a common requirement in iOS and macOS development, whether you are parsing user input, processing API responses, or cleaning up data. When you need to break a single string into multiple pieces based on a delimiter (like a space, comma, or hyphen), you need a reliable splitting mechanism.
Swift provides several methods for this task, but the correct choice depends on the version of Swift you are using and whether you are splitting by a fixed character or by general whitespace.
How to Split a String into an Array
1. Splitting by a Specific Delimiter (Swift 3+)
For modern Swift development, the components(separatedBy:) method is the standard approach. This method takes a String or Character as an argument and returns an array of strings.
If you are splitting by a single space, for example, this is the most direct way:
import Foundation
let fullName = "First Last"
let nameComponents = fullName.components(separatedBy: " ")
// nameComponents is now an array of Strings: ["First", "Last"]
print(nameComponents[0]) // Output: First
2. Splitting by Any Whitespace (Recommended for Names/Addresses)
If your input string might contain multiple spaces, tabs, or newlines between words, using a literal space as the separator will result in empty strings in your array. To handle all types of whitespace, use the split(separator:whereSeparator:) method, which is highly efficient and idiomatic for this purpose.
let messyInput = " Hello World \n Swift! " // Multiple spaces, newlines
let words = messyInput.split(separator: " ", omittingEmptySubsequences: true)
// Note: The result is an array of String.SubSequence, which must be mapped to Strings.
let wordsArray = words.map { String($0) }
print(wordsArray)
// Output: ["Hello", "World", "Swift!"]
3. Using the Global split Function (Advanced)
The global split function is powerful and can be used to split strings based on a closure. This is useful when the delimiter is not a simple character but a pattern or a condition.
let dataString = "apple,banana,cherry"
// Split whenever a comma is found
let fruits = dataString.split(separator: ",")
let fruitsArray = fruits.map { String($0) }
print(fruitsArray)
// Output: ["apple", "banana", "cherry"]
4. Handling Swift 2 Compatibility
If you are maintaining legacy code in Swift 2, the syntax differs significantly. You must use the .characters property on the string to access its CharacterView representation, and then map the results back to String objects.
// Swift 2 Syntax
let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// Accessing elements
let firstName = fullNameArr[0]
How to Prevent Errors and Improve Robustness
1. Always Handle Empty Results
When splitting strings, especially user-provided input, the resulting array may be empty or contain unexpected values. Always check the count of the resulting array before attempting to access an index.
let parts = "OnlyOneName".components(separatedBy: " ")
if parts.count > 1 {
let lastName = parts[1]
} else {
// Handle case where there is no last name
let lastName: String? = nil
}
2. Use String.SubSequence Mapping
Swift’s split functions often return an array of String.SubSequence rather than [String]. To use these results in standard UI components or pass them to functions expecting String, always map the result: split(...).map { String($0) }.
3. Avoid Hardcoding Delimiters for Whitespace
If your goal is to separate words, do not hardcode `
Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.
