本文介绍了条件绑定的初始化程序必须具有可选类型,而不是'String'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在更新为Swift 2.0
错误在if let url = URL.absoluteString
行
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
}
推荐答案
编译器告诉您不能使用if let
,因为它完全没有必要.您没有要解包的任何可选内容:URL
不是可选的,并且absoluteString
属性也不是可选的. if let
仅用于解开可选内容.如果要创建一个名为url
的新常量,请执行以下操作:
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
}
但是,旁注:具有一个名为URL
的参数和一个名为url
的局部常量会令人感到困惑.这样您可能会更好:
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
}
这篇关于条件绑定的初始化程序必须具有可选类型,而不是'String'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!