【问题标题】:Getting 'optional error' after updating Xcode 6 beta 6 to beta 7将 Xcode 6 beta 6 更新到 beta 7 后出现“可选错误”
【发布时间】:2014-09-07 12:19:28
【问题描述】:

我最近将我的 Xcode 6 beta 6 更新为 Xcode 6 beta 7,突然我的部分代码无法编译。我的代码中有这个函数,它在if let layoutManager = textView.layoutManager 行上给出了错误条件绑定中的绑定值必须是可选类型

func textTapped(recognizer: UITapGestureRecognizer){
    self.textHasBeenTapped = true

    if let textView = recognizer.view as? UITextView{
        if let layoutManager = textView.layoutManager {
        // rest of code

        }
    }

我尝试将 textView 设置为如下所示的可选类型(它消除了初始错误),但它却给出了错误 Value of optional type 'CGFloat?'未拆封;你的意思是用'!'或“?”?location.x = textView?.textContainerInset.left 行。如果我在left 之后插入!?,它反而会给我错误:后缀的操作数'!'应该有可选类型; type 是 'CGFloat' 建议我应该删除任何一个 '!'或者 '?'从而形成一种错误循环。

func textTapped(recognizer: UITapGestureRecognizer){
    self.textHasBeenTapped = true

    if let textView: UITextView? = recognizer.view as? UITextView{
        if let layoutManager = textView?.layoutManager {

            var location: CGPoint = recognizer.locationInView(textView)
            location.x = textView?.textContainerInset.left
            // rest of code
        }
    }
}

解决此问题的最佳方法是什么?

【问题讨论】:

    标签: ios xcode swift optional beta


    【解决方案1】:

    您最初的问题实际上源于 UITextView 的 layoutManager 属性在 beta 7 中已更改,因此它不再是 Optional 了。因此它保证不为零,所以你不需要if let... 检查;您可以直接使用该值。

    您将 textView 设置为 Optional 只会导致更多的混乱;您应该将其保留为非可选。

    这是我的写法,一些 cmets 解释了我的更改。

    func textTapped(recognizer: UITapGestureRecognizer) {
        // You didn't need the self bit here.
        textHasBeenTapped = true
    
        // textView should be non-optional, and you don't need to bother
        // specifying the type, as it can be inferred from the cast.
        if let textView = recognizer.view as? UITextView {
    
            // You don't need if let... here as layoutManager is now non-optional
            let layoutManager = textView.layoutManager
            // You don't need to specify the type here, as it can be inferred
            // from the return type of locationInView        
            var location = recognizer.locationInView(textView)
            location.x = textView.textContainerInset.left
            // rest of code
        }    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-07
      • 2015-10-04
      • 2014-10-29
      • 2014-10-13
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多