How to Split a String — Swift 3.0

The following error kept showing up while I tried to split a string by iterating through it using a for-in loop:

Though this error informed me that, unlike arrays, strings can’t be split using a for-in loop, it did not provide guidance on how to fix the error. Naturally, I sought help from Stackoverflow. Below you will find the fruits of my search: two ways to split a string….

Option 1: Add .characters to the end of the string that you would like to split. In the example below, the loop goes through the string and splits it character-by-character (including spaces).

End result:

As you can see on the left, using .characters splits both the words within the string as well as the letters within each word. Depending on the ultimate goal, returning each character of each word within a string might get a little confusing.

However, using .characters to split a string is useful when you would like to change every character within the string. In the example below, I used .characters to replace every character (including spaces) within stringOfWords with an image (“🦄”).

End result:

Option 2: Use components(separatedBy:) to create an array containing each word within the string that you would like to split. In the example below, each word within the string is separated into an array that you can then iterate through using a for-in loop.

End result:

This option is useful when the goal is to change each item (or in this case, word) within the string in the same manner. For instance, in the example below I used components(separatedBy:) to change each word within the stringOfWordsArray into Pig Latin. I did not want each character to change, but rather I wanted each word to be altered in the same way during each iteration (move the first letter of the original word to the end of the word and add “ay”).

End result:

When deciding whether to use .characters or components(separatedBy:), ask yourself “why am I splitting the string? Is my ultimate goal to change/work with every character within the string, or do I want to change/work with every word within the string?” If your answer is the former, then you would use .characters. Conversely, if it is the latter, then you would use components(separatedBy:).

Helpful links below….

components(separatedBy:) — Stackoverflow

Get the nth character of a string — Stackoverflow

Strings and Characters Overview — Apple’s The Swift Programming Language (Swift 3)