There is no trim(). With import Foundation, call text.trimmingCharacters(in: .whitespacesAndNewlines): it removes spaces, tabs and newlines from both ends and returns a new String. For a blank check, test .isEmpty on that result. To trim only the leading side without Foundation, use text.trimmingPrefix(while: \.isWhitespace).
Text from a file, a form or another program often arrives with spaces, tabs or a newline at the ends, and "Ada " == "Ada" is false. Swift's standard library has no method called trim; the usual answer comes from Foundation, and the standard library gives you the pieces to trim one side yourself. The sections below cover trimming both ends, the leading or trailing side only, trimming other characters, collapsing the spaces inside a string, and the invisible Unicode spaces that survive a trim, then a table to pick from. The examples print results in brackets, like [text], so you can see where the spaces went. Each example runs on this page: hit Run, then edit the code and run it again.
1trimmingCharacters(in:): trim both endsRecommended
trimmingCharacters(in:) is a Foundation method, so the file needs import Foundation. It takes a CharacterSet and removes characters in that set from the start and the end, stopping at the first character that is not in it. .whitespacesAndNewlines covers spaces, tabs, line feeds and carriage returns; .whitespaces leaves newlines alone. The original string is not changed: you get a new String back. The same call answers the blank check: a string that is empty after trimming held nothing but whitespace.
import Foundation let raw = " \tHello, Swift! \n" // Both ends: spaces, tabs and newlines let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines) print("[\(trimmed)]") print(raw.count, trimmed.count) // .whitespaces: spaces and tabs only, so the newline stays let keepsNewline = raw.trimmingCharacters(in: .whitespaces) print(keepsNewline.debugDescription) // Only the ends: the spaces inside are kept let city = " New York ".trimmingCharacters(in: .whitespaces) print("[\(city)]") // Blank check: trim, then test isEmpty for input in ["", " ", "\n\t ", " a "] { let isBlank = input.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty print(input.debugDescription, "isEmpty:", input.isEmpty, "blank:", isBlank) }
Output
The tab and the spaces go from the front and the spaces and newline from the back, leaving [Hello, Swift!]; 19 13 shows the original still has all 19 characters. With .whitespaces the result prints as "Hello, Swift! \n": trimming stops at the newline, so the two spaces in front of it stay too. [New York] keeps its inner spaces. In the blank check, isEmpty alone is true only for "", while trimming first also flags " " and "\n\t " as blank: true.
2Leading or trailing only, without Foundation
Foundation has no one-sided version of trimmingCharacters(in:), but the standard library makes both sides short. For the leading side, trimmingPrefix(while: \.isWhitespace) skips characters while they are whitespace; the older drop(while:) does the same. For the trailing side, find the last character that is not whitespace with lastIndex(where:) and slice up to it. Both give a Substring, a view into the original, so wrap the result in String(…) when you store it. An extension on StringProtocol packages them as methods that work on String and Substring alike.
extension StringProtocol {
func trimmingLeadingWhitespace() -> String {
String(drop(while: \.isWhitespace))
}
func trimmingTrailingWhitespace() -> String {
guard let last = lastIndex(where: { !$0.isWhitespace }) else {
return ""
}
return String(self[...last])
}
func trimmed() -> String {
trimmingTrailingWhitespace().trimmingLeadingWhitespace()
}
}
let line = " indented text "
// Leading only: skip characters while they are whitespace
let leading = line.trimmingPrefix(while: \.isWhitespace)
print("[\(leading)]", type(of: leading))
// Trailing only: keep everything up to the last non-whitespace
if let last = line.lastIndex(where: { !$0.isWhitespace }) {
print("[\(line[...last])]")
}
// The extension: String in, String out, no import needed
print("[\(line.trimmingLeadingWhitespace())]")
print("[\(line.trimmingTrailingWhitespace())]")
print("[\(line.trimmed())]")
print("[\("\t \n".trimmed())]")
// It works on a Substring too
let fields = "name: Ada ".split(separator: ":")
print("[\(fields[1].trimmed())]")
Output
trimmingPrefix(while:) gives [indented text ] and its type prints as Substring; the lastIndex(where:) slice gives [ indented text]. The extension methods return the same text as plain String values, and trimmed() gives [indented text]. A string of only whitespace has no last non-whitespace character, so the guard returns "" and the output is []. Called on a Substring from split, the same method turns " Ada " into [Ada].
3Trimming other characters with CharacterSet
trimmingCharacters(in:) takes any CharacterSet, not only the whitespace ones. CharacterSet(charactersIn: "/") builds a set from the characters of a string, and union combines sets, for example whitespace plus .punctuationCharacters. Without Foundation, drop(while:) with a closure trims any leading character you can test for. Keep in mind that a set is a bag of single characters, not a word: to remove an exact prefix such as https://, use trimmingPrefix(_:).
import Foundation // Any characters you list: here the slashes around a path let path = "/usr/local/bin/" let slashes = CharacterSet(charactersIn: "/") print("[\(path.trimmingCharacters(in: slashes))]") // Quotes and dots at either end let quoted = "\"hello\"..." print("[\(quoted.trimmingCharacters(in: CharacterSet(charactersIn: "\".")))]") // Combine sets: whitespace plus punctuation let messy = " ...Done!? " let junk = CharacterSet.whitespaces.union(.punctuationCharacters) print("[\(messy.trimmingCharacters(in: junk))]") // Leading zeros, no Foundation needed print("[\("000420".drop(while: { $0 == "0" }))]") // A set is not a prefix: "https://" means h, t, p, s, : and / let url = "https://swift.org" let wrong = url.trimmingCharacters(in: CharacterSet(charactersIn: "https://")) print("[\(wrong)]") // To remove an exact prefix, use trimmingPrefix print("[\(url.trimmingPrefix("https://"))]")
Output
The slashes go from both ends of the path ([usr/local/bin]), the quotes and dots from the quoted word ([hello]), and the combined set strips the spaces and the punctuation from [Done]. drop(while:) turns 000420 into [420]. The last pair shows the trap: the set built from "https://" also eats the s of swift and leaves [wift.org], while trimmingPrefix("https://") removes exactly that prefix and gives [swift.org].
4Collapsing or removing inner whitespace
Trimming only touches the ends. To turn every run of spaces, tabs and newlines inside a string into a single space, split on whitespace and join the pieces with " ": split drops the empty pieces, so the ends are trimmed in the same step. A regex does the same with replacing; this page compiles in the Swift 5 language mode, so the regex is written with the #/…/# delimiters, which work in every mode. To remove all whitespace, filter the characters.
import Foundation let text = " too many\tspaces \n here " // Collapse: split on any whitespace, join with one space let words = text.split(whereSeparator: \.isWhitespace) print(words) print("[\(words.joined(separator: " "))]") // A regex: each run of whitespace becomes one space let viaRegex = text.replacing(#/\s+/#, with: " ") print("[\(viaRegex)]") print("[\(viaRegex.trimmingCharacters(in: .whitespaces))]") // Remove every whitespace character print("[\(text.filter { !$0.isWhitespace })]")
Output
split(whereSeparator: \.isWhitespace) breaks on the spaces, the tab and the newline alike and returns four words, which joined turns into [too many spaces here]. The regex version keeps one space at each end, [ too many spaces here ], because the runs at the ends become a single space too, so it needs a trim afterwards. filter returns a String with no whitespace left: [toomanyspaceshere].
5No-break spaces and other invisible characters
Text copied from a web page or a word processor often holds a no-break space (U+00A0) instead of a plain one, and files saved on Windows can start with a byte order mark (U+FEFF). They look like a space or like nothing, so a trim that leaves them behind is confusing. Both Character.isWhitespace and the Foundation sets follow Unicode, so some of these count as whitespace and some don't. The program below tests four of them; when your input can contain the ones that survive, add them to the set.
import Foundation // Characters that look like a space, or like nothing at all let suspects: [(name: String, char: Character)] = [ ("U+00A0 no-break space", "\u{00A0}"), ("U+3000 ideographic space", "\u{3000}"), ("U+200B zero-width space", "\u{200B}"), ("U+FEFF byte order mark", "\u{FEFF}"), ] for (name, char) in suspects { let text = "\(char)price\(char)" let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) print(name) print(" isWhitespace: \(char.isWhitespace), trimmed: \(trimmed == "price")") } // Add the leftovers to the set when your input can contain them let invisible = CharacterSet.whitespacesAndNewlines .union(CharacterSet(charactersIn: "\u{200B}\u{FEFF}")) for (_, char) in suspects { let text = "\(char)price\(char)" print("[\(text.trimmingCharacters(in: invisible))]") }
Output
The no-break space and the ideographic space are whitespace by both measures, so a normal trim removes them. The zero-width space is not whitespace for isWhitespace (false), so the standard-library trims in section 2 leave it in place, though .whitespacesAndNewlines removes it on Linux here (trimmed: true). The byte order mark survives both. With U+200B and U+FEFF added to the set, all four inputs come out as [price].
6Which should you use?
| Method | Trims | Foundation | Best for |
|---|---|---|---|
| trimmingCharacters(in: .whitespacesAndNewlines) | Both ends | Yes | Almost everything: input, lines, file contents |
| trimmingCharacters(in: .whitespaces) | Both ends, keeps newlines | Yes | Text where line breaks matter |
| trimmingPrefix(while: \.isWhitespace) | Leading side | No | Removing indentation |
| lastIndex(where:) + slice | Trailing side | No | Trailing spaces, a trim() extension |
| CharacterSet(charactersIn:) | Both ends, your characters | Yes | Slashes, quotes, punctuation, invisible characters |
| split + joined(separator: " ") | Ends and inside | No | Collapsing runs of spaces to one |
Frequently asked questions
Does Swift have a trim method on String?
Not under that name. The usual trim is text.trimmingCharacters(in: .whitespacesAndNewlines), which comes from Foundation, so the file needs import Foundation. Without it, the compiler stops with "value of type 'String' has no member 'trimmingCharacters'". If you want text.trimmed(), write a small extension on StringProtocol, as in section 2.
How do I remove only the leading spaces from a string in Swift?
Use String(text.trimmingPrefix(while: \.isWhitespace)), or the older String(text.drop(while: \.isWhitespace)); both skip characters from the front while they are whitespace and need no import. To remove only spaces and keep tabs, test the character: text.drop(while: { $0 == " " }).
How do I check if a string is empty or only whitespace in Swift?
Trim it and test isEmpty: text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty is true for "", " " and "\n\t ". text.isEmpty alone is true only for "". Without Foundation, text.allSatisfy(\.isWhitespace) gives the same answer for ordinary spaces, tabs and newlines and is also true for an empty string.
Does trimmingCharacters change the original string?
No. It returns a new String and leaves the original as it was, because String is a value type. To update a variable, assign the result back: name = name.trimmingCharacters(in: .whitespaces). To trim every string in an array, map over it: lines.map { $0.trimmingCharacters(in: .whitespaces) }.
Why does trimming "https://" remove letters from my URL?
CharacterSet(charactersIn: "https://") is a set of single characters (h, t, p, s, : and /), and trimming removes any of them from either end. "https://swift.org" loses the s of swift too and becomes wift.org. To remove an exact prefix, use url.trimmingPrefix("https://"), which leaves the string unchanged when the prefix is not there.
Why doesn't trimming remove a no-break space or a byte order mark?
It does remove a no-break space (U+00A0): it counts as whitespace for both trimmingCharacters(in: .whitespacesAndNewlines) and Character.isWhitespace. A byte order mark (U+FEFF) is not whitespace for either, and a zero-width space (U+200B) is not whitespace for isWhitespace, though .whitespacesAndNewlines removes it on Linux here. Add them to the set: CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: "\u{200B}\u{FEFF}")).