One line solution with Swift 4 & 5
As a beginner in Swift and iOS programming I really like @demosthese's solution above with the while
loop as it's very easy to understand. However the example code seems longer than necessary. The following uses essentially the same logic but implements it as a single line while
loop.
// Remove trailing spaces from myString
while myString.last == " " { myString = String(myString.dropLast()) }
This can also be written using the .isWhitespace
property, as in @demosthese's solution, as follows:
while myString.last?.isWhitespace == true { myString = String(myString.dropLast()) }
This has the benefit (or disadvantage, depending on your point of view) that this removes all types of whitespace, not just spaces but (according to Apple docs) also including newlines, and specifically the following characters:
- “\t” (U+0009 CHARACTER TABULATION)
- “ “ (U+0020 SPACE)
- U+2029 PARAGRAPH SEPARATOR
- U+3000 IDEOGRAPHIC SPACE
Note: Even though .isWhitespace
is a Boolean it can't be used directly in the while
loop as it ends up being optional ?
due to the chaining of the optional .last
property, which returns nil
if the String (or collection) is empty. The == true
logic gets around this since nil != true
.
I'd love to get some feedback on this, esp. in case anyone sees any issues or drawbacks with this simple single line approach.