Let\'s assume the following code:
let url = \"http://%20abc\"
let urlString = url.stringByRemovingPercentEncoding!
if urlString != nil {
println(\"done\"
let url = "http://%20abc" let urlString = url.stringByRemovingPercentEncoding! if urlString != nil { println("done") }
The error I get there is on the !=
, where it says:
Binary operator
!=
cannot be applied to operands of the typeString
andnil
Which makes sense. Why would we even want to use any comparison operator between String
and nil
. A String
cannot be nil
.
Now, url.stringByRemovingPercentEncoding
has a return type of String?
, but we're using the implicitly unwrapped optional, which means that urlString
will either be a String
and have a value, or we'll get a fatal error (unexpectedly found nil
unwrapping an optional).
If we remove our implicit unwrap operator:
let url = "http://%20abc"
let urlString = url.stringByRemovingPercentEncoding
if urlString != nil {
println("done")
}
Now the code is perfectly happy. Instead of being a String
, our variable, urlString
is now a String?
. And we can use !=
to compare any optional with nil
because optionals can be nil!
But perhaps the most Swifty way of writing this looks like this:
let url = "http://%20abc"
if let urlString = url.stringByRemovingPercentEncoding {
// do something with urlString
println("done")
}
In this scenario, urlString
is of type String
, so we don't have to unwrap it, but the if
block only enters (and we can only use the urlString
within the if
block) if and only if url.stringByRemovingPercentEncoding
returns a non-nil.
And for the record, if we're not actually going to do anything with urlString
, we have the following two options:
if url.stringByRemovingPercentEncoding != nil {
println("done")
}
and also:
if let _ = url.stringByRemovingPercentEncoding {
println("done")
}