JayUU
JayUU

Reputation: 23

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

I'm a noob in the Swift-Universe, but I have to get the app running ;) It would be great if you help me to find a solution. Thanks a lot in advance.

The Problem occurs after upgrading to newer version of X-Code (Version 9.4.1) and 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

Upvotes: 0

Views: 5431

Answers (2)

Prashant Tukadiya
Prashant Tukadiya

Reputation: 16436

Don't need to use Void use simply stoppedSuccessfully: ((Void) -> ())? and call it with

 let obj:Void = Void()
 stoppedSuccessfully?(obj) 

I don't understand why you have used stoppedSuccessfully it is un necessarily assigned from success which will never been nil so Don't think your condition if self.stoppedSuccessfully != nil will fail

Upvotes: 0

OOPer
OOPer

Reputation: 47876

First change the type of stoppedSuccessfully from (() -> Void)? to ((Void) -> Void)?:

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

Because, when you use Promise<T>, the closure type passed to success is of type (T)->Void. In your code, you are using Promise<Void>, so the type of success is (Void)->Void, not ()->Void.

Thus, your stoppedSuccessfully should be declared as Optional<(Void)->Void>, which is equivalent to ((Void)->Void)?.


And to call the closure of type (Void)->Void, you need to pass one argument of type Void. There's a literal notation of type Void, it's (), an empty tuple.

So, you can replace all success(Void())s to simply success(()).

And you can invoke stoppedSuccessfully in the similar manner:

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

Upvotes: 3

Related Questions