Split a string to characters with split(separator:) in Swift
Overview
The split(separator:) method returns the longest possible sub-sequences of a collection. In this case, we want to use this method to split a string into an array of characters.
Syntax
This is the syntax for the split(separator:) method:
string.split(separator: separatorElement)
Parameters
separatorElement: This is the element that should be split upon.
Return value
The split method returns smaller sub-parts of the array that are obtained from the subject string.
Code example
// create some stringslet numbers = "1 2 3 4"let alphabets = "a-b-c-d"// split strings into characterslet numberCharacters = numbers.split(separator: " ")let alphabetCharacters = alphabets.split(separator: "-")// print resultsprint(numberCharacters)print(alphabetCharacters)
Code explanation
- Lines 2–3: We create two strings,
numbersandstrings. - Lines 6–7: We split the strings into characters.
- Lines 10–11: We print the results to the console.