无法将表达式的类型 'UIImage?' 转换为类型 'Void'

Cannot convert the expression's type 'UIImage?' to type 'Void'

所以我写了一个方法,应该用相机拍照然后 return 那张照片作为 UIImage。但是我一直收到这个奇怪的错误 Cannot convert the expression's type 'UIImage?' to type 'Void',我不知道是什么原因造成的...这是代码:

func captureAndGetImage()->UIImage{
    dispatch_async(self.sessionQueue, { () -> Void in
        // Update orientation on the image output connection before capturing
        self.imageOutput!.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = self.previewLayer!.connection.videoOrientation
        if let device = self.captureDevice{
            self.imageOutput!.captureStillImageAsynchronouslyFromConnection(self.imageOutput!.connectionWithMediaType(AVMediaTypeVideo), completionHandler: { (imageDataSampleBuffer, error) -> Void in
                if ((imageDataSampleBuffer) != nil){
                    var imageData:NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
                    var image = UIImage(data: imageData)
                    return image
                }
            })
        }
    })
}

我也试过 return image as UIImage 但也没用。 我的猜测是与完成处理程序有关。

谢谢!

问题是您将其视为同步操作,但它是异步的。您不能只 return 来自异步操作的图像。您将不得不重写您的方法以获取一个完成块,然后在您检索图像时执行该块。我将其重写为如下内容:

func captureAndGetImage(completion: (UIImage?) -> Void) {
    dispatch_async(self.sessionQueue, { () -> Void in
        // Update orientation on the image output connection before capturing
        self.imageOutput!.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = self.previewLayer!.connection.videoOrientation
        if let device = self.captureDevice{
            self.imageOutput!.captureStillImageAsynchronouslyFromConnection(self.imageOutput!.connectionWithMediaType(AVMediaTypeVideo), completionHandler: { (imageDataSampleBuffer, error) -> Void in
                var image: UIImage?
                if ((imageDataSampleBuffer) != nil){
                    var imageData:NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
                    image = UIImage(data: imageData)
                }
                completion(image)
            })
        }
    })
}