Swift 4: 无法将类型“(Void) -> Void”的值分配给类型“(() -> Void)?”

Swift 4: Cannot assign value of type '(Void) -> Void' to type '(() -> Void)?'

我是 Swift-Universe 中的菜鸟,但我必须下载应用程序 运行 ;) 如果您能帮助我找到解决方案,那就太好了。非常感谢。

升级到较新版本的 X-Code(版本 9.4.1)和 Swift 4.

后出现问题
private var stoppedSuccessfully: (() -> Void)?

func stopRecording() -> Promise<Void> {

    return Promise { success, _ in

        self.stoppedSuccessfully = success // The error occors here: Cannot assign value of type '(Void) -> Void' to type '(() -> Void)?'


        if WCSession.default.isReachable {
            logger.info("Watch is reachable - Send Stop recording message.")
            let command = RecordingCommand.stop

            self.sendMessage(command, EvomoWatchConnectivityCore.WatchConnectivityCoreMethod.transferUserInfo,
                             nil, nil)

            // Create a Timeout
            let timeoutDelay: Double = 15

            DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + timeoutDelay) {

                if self.stoppedSuccessfully != nil {
                    self.logger.warning("### Stopped waiting for Apple Watch recording by Timeout!")
                    success(Void())
                    self.stoppedSuccessfully = nil
                }

            }

            return
        }

        success(Void())
        self.stoppedSuccessfully = nil

    }

}

// In a other part of the code:
self.stoppedSuccessfully?()
self.stoppedSuccessfully = nil

不需要使用 Void 只需使用 stoppedSuccessfully: ((Void) -> ())? 并用

调用它
 let obj:Void = Void()
 stoppedSuccessfully?(obj) 

我不明白你为什么使用 stoppedSuccessfully 它不一定是从 success 分配的,它永远不会 nil 所以不要认为你的情况 if self.stoppedSuccessfully != nil 会失败

先把stoppedSuccessfully的类型从(() -> Void)?改成((Void) -> Void)?:

private var stoppedSuccessfully: ((Void) -> Void)?

因为,当你使用Promise<T>时,传递给success的闭包类型是(T)->Void类型。在您的代码中,您使用的是 Promise<Void>,因此 success 的类型是 (Void)->Void,而不是 ()->Void

因此,您的 stoppedSuccessfully 应声明为 Optional<(Void)->Void>,相当于 ((Void)->Void)?


而要调用 (Void)->Void 类型的闭包,您需要传递一个 Void 类型的参数。有一个 Void 类型的文字符号,它是 (),一个空元组。

因此,您可以将所有 success(Void()) 替换为简单的 success(())

您可以用类似的方式调用 stoppedSuccessfully

// In a other part of the code:
self.stoppedSuccessfully?(())