【问题标题】:Cannot assign value of type '() -> Void' to '(() -> Void)!'无法将“() -> Void”类型的值分配给“(() -> Void)!”
【发布时间】:2016-10-05 13:35:15
【问题描述】:

由于我使用 Swift 3 出现以下错误..

无法将类型 '(LLSimpleCamera?, NSError?) -> Void' 的值分配给 输入'((LLSimpleCamera?, Error?) -> Void)!'

有人知道该怎么做吗? 这是我的代码..

camera.onError = { (camera: LLSimpleCamera?, error: NSError?) -> Void in
        print("Camera error: \(error)")

        if error.domain == LLSimpleCameraErrorDomain {
            if error.code == Int(LLSimpleCameraErrorCodeCameraPermission.rawValue) || error.code == Int(LLSimpleCameraErrorCodeMicrophonePermission.rawValue) {

                let alertVC = UIAlertController(title: "Ooops!", message: "We need permission for the camera. Please go to your settings.", preferredStyle: .alert)
                let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                let settingsAction = UIAlertAction(title: "Settings", style: .default) { (action) in
                    UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
                }

                alertVC.addAction(okAction)
                alertVC.addAction(settingsAction)

                self.present(alertVC, animated: true, completion: nil)
            }
        }
    }

【问题讨论】:

  • 您可以尝试将camera.onError = { (camera: LLSimpleCamera?, error: NSError?) -> Void in … 替换为camera.onError = { (camera: LLSimpleCamera?, error: Error?) -> Void in … 吗?
  • 是的,你是对的!但是现在 Xcode 说错误没有类型的域和代码.. 你知道如何解决这个问题吗?
  • 好吧,我猜你必须使用as? 将错误转换为NSError。问题是在 Swift 3 之前有协议 ErrorType 和旧的 Objective C 类 NSError,但在 Swift 中,在命名简化的方式上,两者现在都称为 Error(它没有域和其他属性),并且所有 @ 987654329@s 个 ObjC 映射到它。
  • 好的,我会将之前的评论信息复制到答案中,只是为了回答问题。

标签: ios swift casting swift3


【解决方案1】:

Swift 3 将 Objective C NSError 类型映射到协议 Erroraka ErrorType in Swift 2)。

因此,在闭包参数列表中,它期望 Error 作为第二个参数的类型,而不是 NSError

但是如果你想使用.domain/.code/etc,你需要在闭包里面输入error参数到NSError

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多