HomeSearch

Swift Split Strings Example (components)

Use components separatedBy to split a string into an array. Split with a string or characters.
Split. A string has multiple parts separated by special characters (delimiter characters). We can separate these parts into a String array.
In Swift, there is no special split method. But we invoke components(), part of the Foundation library, with a separatedBy argument. This works well for splitting strings.
Initial example. Let us begin by splitting apart a string containing tasty fruits. The string contains apple, peach and kiwi, separated by commas.

Method: We invoke components() on the input string. We specify the separatedBy argument name. We pass a delimiter string.

Result: A String array containing 3 strings is returned. Its count is 3, and we loop over and print the string data.

Swift program that splits with components, separatedBy import Foundation // An example string separated by commas. let line = "apple,peach,kiwi" // Use components() to split the string. // ... Split on comma chars. let parts = line.components(separatedBy: ",") // Result has 3 strings. print(parts.count) print(parts) // Loop over string array. for part in parts { print(part) } Output 3 ["apple", "peach", "kiwi"] apple peach kiwi
Multiple chars. Sometimes a string contains many delimiter chars, not just one. For example this string has a colon, comma and semicolon for delimiters.

Method: The components() charactersIn method handles this case. We must pass it a CharacterSet.

Note: A CharacterSet can be constructed with an init method that receives a string. Each character in the string is added to the set.

Result: The four letters (single-character strings) are added to the result array. We loop over and display them.

For
Swift program that splits on multiple chars import Foundation // This line has three different separators. let line = "a:b,c;d" // Create a CharacterSet of delimiters. let separators = CharacterSet(charactersIn: ":,;") // Split based on characters. let parts = line.components(separatedBy: separators) // Print result array. print(parts) // Loop over strings that were split apart. for part in parts { print(part) } Output ["a", "b", "c", "d"] a b c d
EnumerateLines. Often we just want to loop over lines in a string. With enumerateLines, we do not get a string array. We pass a closure to process each line in the string.

Tip: This func handles different kinds of line separators, for UNIX and Windows. It is part of Foundation.

Swift program that uses enumerateLines import Foundation // This string contains three lines. let source = "cat\ndog\r\nbird" // Enumerate lines in the string. source.enumerateLines { (line, stop) -> () in print(line) } Output cat dog bird
Remove empty entries. Sometimes we get an empty string when we separate a string into an array. With filter, we can eliminate empty strings.

Here: The "schools" array has two empty strings. We use isEmpty in filter to remove those. We print our results.

Swift program that splits, removes empty entries import Foundation // This string contains some empty sections. let data = "Harvard; Princeton; ; ; Yale"; // Split on the delimiter. let schools = data.components(separatedBy: "; ") // Use filter to eliminate empty strings. let nonempty = schools.filter { (x) -> Bool in !x.isEmpty } // Print before and after results. print(schools) print(nonempty) Output ["Harvard", "Princeton", "", "", "Yale"] ["Harvard", "Princeton", "Yale"]
Joined. In Swift we use the joined method to combine strings in a string array together. Join is the opposite of components(). We often use them together.Join
A note, Swift 3. For Swift 3, we use components() with a separatedBy argument instead of componentsSeparatedByString. This syntax is easier to read and type.
To summarize: Swift offers no string split() method. Instead we use the Foundation method that separates strings. Components() just splits strings based on the arguments.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls