ios - 将 Xcode 6 beta 6 更新到 beta 7 后获取 'optional error'

标签 ios xcode swift option-type beta

我最近将我的 Xcode 6 beta 6 更新为 Xcode 6 beta 7,突然我的部分代码无法编译。我的代码中有这个函数,它在 if let layoutManager = textView.layoutManager 行中给出错误 Bound value in a conditional binding must be of Optional type

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 之后插入 !?,它反而给我错误:Operand of postfix '!'应该有可选类型; 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
        }
    }
}

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

最佳答案

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

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

我会这样写,并附上一些解释我所做更改的注释。

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
    }    
}

关于ios - 将 Xcode 6 beta 6 更新到 beta 7 后获取 'optional error',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25710084/

相关文章:

ios - 使用AFNetworking与OCMock的测试方法

iphone - iOS 5 中 Xcode 4.2 中的新 "objects library"

ios - swift 3 : How to determine a downloaded file's internet speed?

iphone - 从其 subview 中删除WEPPopover

swift - 如何在 Swift 中为状态设置属性标题颜色

swift - 如何使用 Swift 3 中的 sampleBuffer、captureOutput 将视频保存到文件?

iOS 7 UITextView 错误

ios - 通过带有 UDID 的 IPA 分发给客户端?

objective-c - 有没有办法知道哪个 Collection View 单元格在特定点?

ios - 将签名身份和临时配置文件从一台 Mac 导出和导入到另一台 Mac