String Trimming in Swift: Is There a trim() Method for String?

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

"Where's my .trim()?" — or Why Swift is Not Python

\n\n

If you came to Swift from Python or JavaScript, you're probably used to the simple call " hello ".trim() or " hello ".strip(). And so you write your first Swift code, try to do the same thing — and get a compilation error. Sound familiar?

\n\n

On Stack Overflow, this question has garnered thousands of views, and for good reason. In Swift, there is no .trim() method on String. But that doesn't mean you can't trim whitespace and characters. The approach is just different — more Swift-way. Let's figure it out once and for all.

\n\n

In this article, we'll not only answer the main question but also show real code examples that you can immediately insert into your project. Let's go!

\n\n

Short Answer: Yes, But Not How You're Used To

\n\n

In Swift, there is no single .trim() method. Instead, a family of methods from the Foundation protocol is used:

\n\n
    \n
  • trimmingCharacters(in:) — the main tool
  • \n
  • .trimmingCharacters(in: .whitespacesAndNewlines) — the most popular option
  • \n
\n\n

Sounds terse? In practice, this gives you flexibility: you decide exactly which characters you want to trim, rather than relying on the "magic" of a built-in method.

\n\n

How trimmingCharacters Works — Breakdown with Examples

\n\n

Basic Example: Removing Spaces and Line Breaks

\n\n
import Foundation\n\nlet text = "   Hello, Swift!   \\n"\nlet trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)\nprint(trimmed) // "Hello, Swift!"
\n\n

Note: we must import Foundation. Without it, the method is unavailable, as it is defined in NSString, which is "bridged" to the Swift String.

\n\n

Only Spaces (Without Removing Line Breaks)

\n\n
let textWithNewline = "  Hello\\n"\nlet onlySpacesTrimmed = textWithNewline.trimmingCharacters(in: .whitespaces)\nprint(onlySpacesTrimmed) // "Hello\\n"
\n\n

See? The line break remains. This is convenient when you want to preserve formatting but remove extra spaces at the edges.

\n\n

Trimming Arbitrary Characters

\n\n

You can pass any set to CharacterSet:

\n\n
let email = "  user@example.com  "\nlet cleaned = email.trimmingCharacters(in: .whitespaces)\nprint(cleaned) // "user@example.com"\n\nlet price = "$99.99"\nlet noDollar = price.trimmingCharacters(in: CharacterSet(charactersIn: "$"))\nprint(noDollar) // "99.99"
\n\n

What About trimLeft / trimRight (ltrim / rtrim)?

\n\n

In Python, there are .lstrip() and .rstrip(). In Swift — there aren't. But this is easy to implement manually. Here are two simple extensions you can add to your project:

\n\n
import Foundation\n\nextension String {\n    func trimmingLeft(in characterSet: CharacterSet = .whitespacesAndNewlines) -> String {\n        var start = startIndex\n        while start < endIndex, characterSet.contains(self[start].unicodeScalars.first!) {\n            formIndex(after: &start)\n        }\n        return String(self[start..<endIndex])\n    }\n    \n    func trimmingRight(in characterSet: CharacterSet = .whitespacesAndNewlines) -> String {\n        var end = endIndex\n        while end > startIndex, characterSet.contains(self[index(before: end)].unicodeScalars.first!) {\n            formIndex(before: &end)\n        }\n        return String(self[startIndex..<end])\n    }\n}\n\n// Usage example:\nlet text = "   Hello World   "\nprint(text.trimmingLeft())  // "Hello World   "\nprint(text.trimmingRight()) // "   Hello World"
\n\n

Now you have full-fledged trimLeft and trimRight, just like in your beloved Python. Save this code in a separate file — it will come in handy.

\n\n

P

Blogs

Book Recommendations