Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

swift - Initializer for conditional binding must have Optional type, not '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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...