条件绑定的初始化程序必须具有可选类型,而不是'String'
收藏

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

func myFormatCompanyMessageText(attributedString: NSMutableAttributedString) -> NSMutableAttributedString
{
    // Define text font
    attributedString.addAttribute(NSFontAttributeName, value: UIFont(name: "Montserrat-Light", size: 17)!, range: NSMakeRange(0, attributedString.length))

    return attributedString
}

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

最佳答案

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
}

    公众号
    关注公众号订阅更多技术干货!