可选类型 "CGContext?" 的值未展开

value of optional type "CGContext?" not unwrapped

我尝试在视图中画一条线,但由于可选类型错误,我的代码无法编译。我是 swift 和 objective-c 的新手,花了很多时间来搜索答案。问题至今没有解决。那么,任何人都可以提供一些解决此问题的线索吗?

代码:

import UIKit

class DrawLines: UIView {

       // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
         //Drawing code
        // context
      let context = UIGraphicsGetCurrentContext()
      CGContextSetLineWidth(context, 3.0)
      CGContextSetStrokeColorWithColor(context, UIColor.purpleColor().cgColor)

      //create a path
      CGContextMoveToPoint(context,0,0)
      CGContextAddLineToPoint(context,250,320)

    }
}

错误:

UIGraphicsGetCurrentContext() returns 可选,要在您的示例中使用它,您需要调用 context!。 最好的使用方法是将它包装在 if-let:

if let context = UIGraphicsGetCurrentContext() {
    // Use context here
}

或者更好地使用 guard let:

guard let context = UIGraphicsGetCurrentContext() else { return }
// Use context here

在这种情况下,解决方案是在获取上下文时使用 !

let context = UIGraphicsGetCurrentContext()!

当没有当前上下文时,应用程序会崩溃,这意味着您做错了。

只是强制展开上下文,100% 安全但只解决了一个问题。

来自 UIGraphicsGetCurrentContext 的文档:

The current graphics context is nil by default. Prior to calling its drawRect: method, view objects push a valid context onto the stack, making it current.

在 Swift 3 中(根据 draw 签名假设)图形语法发生了显着变化:

class DrawLines: UIView {

    override func draw(_ rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()!
        context.setLineWidth(3.0)
        context.setStrokeColor(UIColor.purple.cgColor)

        //create a path

        // context.beginPath()
        context.move(to: CGPoint())
        context.addLine(to: CGPoint(x:250, y:320))
        // context.strokePath()

    }
}

PS:但要划清界线,您应该取消注释 beginPath()strokePath() 行。