dispatch_async() 与 throwables swift 2 Xcode 7

dispatch_async() with throwables swift 2 Xcode 7

尝试使用 dispatch_async,其中我需要一个可抛出的调用,但是 Swift 的新错误处理和方法调用让我感到困惑,如果有人能告诉我如何正确地做到这一点, 或者指出正确的方向,我将不胜感激。

代码:

func focusAndExposeAtPoint(point: CGPoint) {
    dispatch_async(sessionQueue) {
        var device: AVCaptureDevice = self.videoDeviceInput.device

        do {

            try device.lockForConfiguration()
            if device.focusPointOfInterestSupported && device.isFocusModeSupported(AVCaptureFocusMode.AutoFocus) {
                device.focusPointOfInterest = point
                device.focusMode = AVCaptureFocusMode.AutoFocus
            }

            if device.exposurePointOfInterestSupported && device.isExposureModeSupported(AVCaptureExposureMode.AutoExpose) {
                device.exposurePointOfInterest = point
                device.exposureMode = AVCaptureExposureMode.AutoExpose
            }

            device.unlockForConfiguration()
        } catch let error as NSError {
            print(error)
        }
    }
}

警告:

: Invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '@convention(block) () -> Void'

最终编辑:此错误已在 Swift 2.0 final(Xcode 7 final)中修复。

改变

} catch let error as NSError {

} catch {

效果完全一样 — 您仍然可以 print(error) — 但代码将编译,您将继续使用。

编辑 这就是为什么我认为(正如我在评论中所说)您发现的是一个错误。这编译得很好:

func test() {
    do {
        throw NSError(domain: "howdy", code: 1, userInfo:nil)
    } catch let error as NSError {
        print(error)
    }
}

编译器不会抱怨,特别是不会强迫你写 func test() throws — 从而证明编译器认为这个 catch 是详尽无遗的。

但这不能编译:

func test() {
    dispatch_async(dispatch_get_main_queue()) {
        do {
            throw NSError(domain: "howdy", code: 1, userInfo:nil)
        } catch let error as NSError {
            print(error)
        }
    }
}

但它是完全相同的 do/catch 方块!那么为什么它不在这里编译呢?我认为这是因为编译器以某种方式被周围的 GCD 块混淆了(因此错误消息中关于 @convention(block) 函数的所有内容)。

所以,我的意思是,要么它们都应该编译,要么它们都不能编译。我认为一个存在而另一个不存在的事实是编译器中的错误,我正是基于此提交了错误报告。

编辑 2:这是说明错误的另一对(来自@fqdn 的评论)。这编译:

func test() {
    dispatch_async(dispatch_get_main_queue()) {
        do {
            throw NSError(domain: "howdy", code: 1, userInfo:nil)
        } catch is NSError {

        }
    }
}

但是这个 确实 可以编译,即使它是完全相同的东西:

func test() {
    func inner() {
        do {
            throw NSError(domain: "howdy", code: 1, userInfo:nil)
        } catch is NSError {

        }
    }
    dispatch_async(dispatch_get_main_queue(), inner)
}

不一致就是错误。