How to trim whitespaces in a Swift string?


Developers often need to work with string while developing iOS apps or apps for any other Apple devices. One of the most frequent tasks to perform on a string is trimming whitespaces.

To trim whitespace, there is trimmingCharacters() method in the Foundation library.

In this tutorial, I am going to show you how to remove the leading and trailing whitespaces from a string using the trimmingCharacters().

First of all, let’s see how to use the trimmingCharacters()method:

string.trimmingCharacters(in: .whitespaces)

In the above syntax, string is the object of a String class

whitespaces is the property that can remove whitespaces from both sides of a Swift string.

Now let’s see the code below to remove whitespaces from both ends:

import Foundation

var myText = "     SwiftSpeedy is amazing    "

// remove whitespaces from both sides
var newText = myText.trimmingCharacters(in: .whitespaces)

print(newText)

Output:

SwiftSpeedy is amazing

As you can see, we have successfully been able to trim our string.

You can also remove new lines along with whitespaces by using the property whitespacesAndNewlines with the trimmingCharacters() method. Below given how we can do it:

import Foundation

var myText = "  \n   SwiftSpeedy is amazing \n\n\n\n   "

// remove whitespaces and new lines from both sides
var newText = myText.trimmingCharacters(in: .whitespacesAndNewlines)

print(newText)

Output:

SwiftSpeedy is amazing