The best and easy way without using scripts, hacks and much more. Just go to Find And Replace and press alt/option + space and press space button in the replace bar and then click on replace all. It will replace the whitespaces with normal spaces and the warning/ error will be gone !!
Trim leading and trailing spaces To remove leading and trailing spaces, we use the trimmingCharacters(in:) method that removes all characters in provided character set. In our case, it removes all trailing and leading whitespaces, and new lines.
To remove all leading whitespaces, use the following code: var filtered = "" var isLeading = true for character in string { if character. isWhitespace && isLeading { continue } else { isLeading = false filtered. append(character) } } print(filtered) // "Hello, World! "
Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.
Starting from Xcode 4.4 whitespaces will be trimmed automatically by default, unless the line is all whitespace. You can also activate Including whitespace-only lines
to fix this, which is not active by default.
Go to Xcode > Preferences > Text Editing > While editing
I'm using the Google Toolbox For Mac Xcode Plugin, it adds a "Correct whitespace on save" parameter that trim trailing whitespace on save. I missed that a lot from emacs.
You can create a script and bind it to a keyboard shortcut:
Then enter the following script:
#!/usr/bin/perl
while (<>) {
s/\s+$//;
print "$_\n";
}
I find using the new Automatically trim trailing whitespace -> Including whitespace-only lines
as suggested by @MartinStolz works well while editing but I sometimes need to do Cmd + a -> Ctrl + i and save the file multiple times with the file in focus when I'm not editing.
In case you want to clean a whole project (excluding .md
files) without using scripts, you can also do a Find & Replace -> Regular Expression
. Since this technique removes trailing space and tabs for documentation/comments as well, you can also try a negative lookahead for blacklisted characters to filter out single-line comments.
[\t ]+$
^(?!.*\\\\)[\t ]+$
<nothing>
So linting can also be done without swiftlint autocorrect
or similar third party solutions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With