So if string is not NilLiteralConvertible… what do some string functions return?

后端 未结 1 932
春和景丽
春和景丽 2020-12-22 13:39

Let\'s assume the following code:

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


        
相关标签:
1条回答
  • 2020-12-22 14:25
    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 type String and nil

    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")
    }
    
    0 讨论(0)
提交回复
热议问题