function with @discarableResult can't be used when ()->Void is expected

I know that @discarableResult suppresses the warning when you don't use the return value when calling a function, but shouldn't it allow the function to be used in other cases where no return value is used?


For example, let's say I have a function that attempts an action and returns whether it succeeded, I would like to call it for each element in a list but this code doesn't compile:

@discardableResult
func attemptAction(with input: Int) -> Bool {
    // ** attempt some action and determine whether it succeeded **
    let succeeded = (input != 3)
    return succeeded
}
let data = [1,2,3,4,5]
data.forEach(attemptAction) //ERROR: Cannot convert value of type '(Int) -> Bool' to expected argument type '(Int) -> Void'


I would expect the @discardableResult to express that the function can be used as `(Int) -> Bool` or as `(Int) -> Void` when the result is discarded.


I see this as an oversight and would like to report it to radar but I want to make sure I'm not missing something obvious before I do.

Thank you.

Replies

The thing is, the existence of @discardableResult doesn't necessarily mean that it's a good idea to use it. (I mean, when designing your own APIs, to decide that a result won't commonly be used, and to add the @discardableResult annotation to reflect that.)


Your API would be clearer if you simply provide two methods, one that returns a result and one that doesn't. Hopefully, the first would be named to indicate a boolean outcome ("didTakeAction"), and the second's name wouldn't leave the reader wondering why it doesn't matter whether an "attempt" fails.


In fact, I can't think of a good direct reason why your "attemptAction" function shouldn't work as a closure of the expected type as you wish, but I can think of reasons why you shouldn't write the function that way.