Initializer for conditional binding must have Optional type, not 'String'

前端 未结 2 1332
小鲜肉
小鲜肉 2020-12-17 08:21

Here is a fun issue I\'m running into after updating to Swift 2.0

The error is on the if let url = URL.absoluteString line

         


        
相关标签:
2条回答
  • 2020-12-17 08:30

    absoluteString isn't an optional value, its just a String. You can check if the URL variable is nil

    if let url = yourURLVariable {
        // do your textView function
    } else {
        // handle nil url
    }
    
    0 讨论(0)
  • 2020-12-17 08:44

    The compiler is telling you that you can't use an if let because it's totally unnecessary. You don't have any optionals to unwrap: URL is not optional, and the absoluteString property isn't optional either. if let is used exclusively to unwrap optionals. If you want to create a new constant named url, just do it:

    func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
        let url = URL.absoluteString
        if #available(iOS 8.0, *) {
            VPMainViewController.showCompanyMessageWebView(url)
        }
        return false
    }
    

    However, sidenote: having a parameter named URL and a local constant named url is mighty confusing. You might be better off like this:

    func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool {
        if #available(iOS 8.0, *) {
            VPMainViewController.showCompanyMessageWebView(URL.absoluteString)
        }
        return false
    }
    
    0 讨论(0)
提交回复
热议问题