let url = "http://%20abc" let urlString = url.stringByRemovingPercentEncoding! if urlString != nil { println("done") }
The error I get is on != , Which says:
The binary operator != Cannot be applied to operands of type String and nil
It makes sense. Why do we even want to use any comparison operator between String and nil . A String cannot be nil .
Now url.stringByRemovingPercentEncoding has a String? return type String? , but we use an implicitly expanded option, which means that urlString will either be String , or have a value, or we will get a fatal error (unexpectedly found nil option is expanded).
If we remove our implicit reversal operator:
let url = "http://%20abc" let urlString = url.stringByRemovingPercentEncoding if urlString != nil { println("done") }
Now the code is completely happy. Instead of String our urlString variable now String? . And we can use != To compare any optional with nil , because options can be nil!
But perhaps the most Swifty way of writing is as follows:
let url = "http://%20abc" if let urlString = url.stringByRemovingPercentEncoding { // do something with urlString println("done") }
In this case, urlString is of type String , so we do not need to expand it, but the if block is included only (and we can use only urlString in if block) if and only if url.stringByRemovingPercentEncoding returns non-nil.
And for the record, if we really won't do anything with urlString , we have the following two options:
if url.stringByRemovingPercentEncoding != nil { println("done") }
and:
if let _ = url.stringByRemovingPercentEncoding { println("done") }