#04: Splitting Strings in Swift

Splitting and trimming are likely the two more common operation we perform on strings.

In Swift, you can split strings in two ways, depending on the fact that you prefer a pure-Swift solution or if you decide to import Foundation.

The Swift way

The 100% Swift solution involves splitting the character array with the string’s content into a series of sub-arrays using a separator and then converting those sub-arrays into classic string using map.


let line = "Brevity is the soul of wit"
let words = line.characters.split(separator:" ").map(String.init)

words[0] // Brevity
words[5] // wit

Or if you need to perform more complex checks on the separator, you can use:


let words = line.characters.split{$0 == " "}.map(String.init)

words[0] // Brevity
words[5] // wit

To learn more about map and flatMap, check out this post.

The Foundation way

If you can import Foundation into your project, as in many other situations, NSString already have the method we need, in this case a components method that splits out string in substrings:


import Foundation

let words = line.components(separatedBy: " ")

words[0] // Brevity
words[5] // wit

Did you like this article? Let me know on Twitter or subscribe for updates!


I'm also on Twitter and GitHub.

Subscribe via RSS or email.