33

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
}
Simply Ged
  • 8,250
  • 11
  • 32
  • 40
mosaic6
  • 923
  • 3
  • 11
  • 18

3 Answers3

58

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
}
andyvn22
  • 14,696
  • 1
  • 52
  • 74
  • can we use guard here? – iPhone 7 Aug 31 '17 at 12:25
  • @iPhone6 No, for the same reason you can't use `if let`: because `URL.absoluteString` *always* succeeds. There's nothing to guard against--`absoluteString` is non-optional and will never be `nil`. – andyvn22 Aug 31 '17 at 15:41
0

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
}
Chris Slowik
  • 2,859
  • 1
  • 14
  • 27
0

Note: with reference to the question

Guard or if conditions are used to make sure if the values is not present it should not crash. but the function argument makes sure (URL: NSURL) will come, or any scenario which makes sure the values do come there no need to check with if let or guard statement. That is what compiler is educating developer. try removing the if let or guard statement in such case it should work

Ullas Pujary
  • 349
  • 4
  • 14