I know that I should use @discardableResult
. So I have the following code:
@discardableResult func someFunc() { ... }
Then I just call it:
someFunc()
But if I have and use a pointer to this method then it doesn't work again. For example:
let someFunc = self.someFunc
someFunc() //unused warning
Is it possible to avoid _=someFunc()
in this case?
Unfortunately, discardableResult
only applies to method/function declarations. What you can do is to wrap the value-returning function in a void-returning closure:
@discardableResult
func f() -> Int { return 1 }
// the type annotation here is important
let someFunc: () -> Void = { f() }
Alternatively, write a function that "erases" the return type of functions:
func discardResult<R>(_ f: @escaping () -> R) -> (() -> Void) {
{ _ = f() }
}
let someFunc = discardResult(f)
The downside is that you need to write an overload of this for each arity:
func discardResult<T, R>(_ f: @escaping (T) -> R) -> ((T) -> Void) {
{ x in _ = f(x) }
}
func discardResult<T, U, R>(_ f: @escaping (T, U) -> R) -> ((T, U) -> Void) {
{ x, y in _ = f(x, y) }
}
func discardResult<T, U, V, R>(_ f: @escaping (T, U, V) -> R) -> ((T, U, V) -> Void) {
{ x, y, z in _ = f(x, y, z) }
}
// and so on