0

Due to the lack of generic support in typealias definitions in Swift, I wrote a generic ResultHandler<T> callback like so:

struct ResultHandler<T> {
    let f: (result: T) -> ()
}

This works great for handlers that use anything other than Void:

Dispatch<Bool>.dispatch({ () -> (Result<Bool>) in
    Result<Bool>(true)
}).onResult(ResultHandler() { (result: Bool) in
    if result {
        self.doSomething() // Method executes successfully
    }
})

But when attempting to use Void:

Dispatch<Void>.dispatch({ () -> (Result<Void>) in
    Result<Void>()
}).onResult(ResultHandler() { (result: Void) in // Compiler error here
    self.doSomething()
})

There is a compilation error:

Function signature '(Void) -> ()' is not compatible with expected type '(result: Void) -> ()'

Which seems misleading/a compiler bug, as if I change the signature to use a wrongly-typed value:

Dispatch<Void>.dispatch({ () -> (Result<Void>) in
    Result<Void>()
}).onResult(ResultHandler() { (result: Void?) in // Compiler error here
    self.doSomething()
})

The error message picks up the optional-indicating ?, but still does not properly detect my result: label:

Function signature '(Void?) -> ()' is not compatible with expected type '(result: Void) -> ()'

What am I doing wrong?

1 Answer 1

1

You don't need to specify parameter names in closure type declarations—that's what's giving the compiler problems:

struct ResultHandler<T> {
    let f: T -> ()
}

Now you can create ResultHandler instances that use a Bool parameter, a Void parameter, or leave out the parameter altogether:

let r1 = ResultHandler() { (result: Bool) in
    if result {
        // do something
    }
}

let r2 = ResultHandler() { (_: Void) in
    // do something
}

let r3 = ResultHandler() {
    // do something
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.