Splitting Strings in Swift

SplittingStrings.png

So this actually came up at work the other day and I felt like it was a good thing to write up for others in case they come across anything similar while building apps using Swift. The problem was a string sent back from the server needed to be split up into two strings - a title and a description. The title and description were separated by a special character, which made splitting the string up super easy.

Let’s take the following string as an example:

Splitting Strings&How to do it in Swift

We want to split the string into two components; one for the title “Splitting Strings” and one for the description “How to do it in Swift.” To do that, we’ll use components(separatedBy:)

let sourceString = "Splitting Strings&How to do it in Swift"
let stringComponents = sourceString.components(separatedBy: "&")

Now stringComponents is an array of our two strings that can be used on their own, with the separator “&” thrown out. Quick and easy!

Check out some other recent tutorials

Previous
Previous

How to Make Custom List Rows

Next
Next

How to Set the Background Color in SwiftUI