So, if the string is not NilLiteralConvertible ... what do some string functions return?

Suppose the following code:

let url = "http://%20abc" let urlString = url.stringByRemovingPercentEncoding! if urlString != nil { println("done") } 

stringByRemovingPercentEncoding should return an optional string. So let's deploy it. Now, what happens when it actually "crashes" and does not return a string?

String is not NilLiteralConvertible, so a compiler error occurs on the next line. I am really confused here - so should I compare with urlString if I assume url.stringByRemovingPercentEncoding is expanded optional? Obviously, it does not work with nil.

Note that I can leave urlString as an optional value and then expand it, etc. This is not true. The fact is that this is an exact case. Many thanks!

-2
ios swift optional
source share
1 answer
 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") } 
+3
source share

All Articles