In the above, quote.trim()
seems to be fine as the right sidebar in playground shows the expected text. But then when I print it, I just get ()\n
. Have I done something wrong?
The problem is that quote.trim()
does not return a value, i.e., it returns Void
. In Swift, Void
is defined as an empty tuple ()
. So that's what you're getting in the print
statement.
In other words, this:
mutating func trim() {
self = self.trimmed()
}
is the same as this:
mutating func trim() -> Void {
self = self.trimmed()
}
is the same as this:
mutating func trim() -> () {
self = self.trimmed()
}
and the print
is getting that ()
output from trim
and dumping it into the console.
Make sense?
So the correct way to do what you are attempting would be either to use the mutating function on quote
and then put quote
into a print
, like so:
quote.trim()
print(quote)
or use the trimming
function, which returns a String
:
print(quote.trimming())
The difference being, of course, that using trimming
does not alter the value of quote
but returns a new String
that is the same as quote
but with the whitespace stripped out. quote
still has the same value it had before you called trimming
. Whereas by using trim
, you are altering the value of quote
so that when you use it later, it will have that altered value rather than the original value.