Using @discardableResult to close in Swift

Swift 3 introduced annotations @discardableResultfor functions to disable warnings for the return value of an unused function.

I am looking for a way to silence this warning for closing.

Currently, my code looks like this:

func f(x: Int) -> Int -> Int {
  func g(_ y: Int) -> Int {
    doSomething(with: x, and: y)
    return x*y
  }
  return g
}

In different places, I call fonce to get a closure g, which I then call again:

let g = f(5)
g(3)
g(7)
g(11)

doSomething, g. Swift 3 . , g _ = g(...) ? , @discardableResult.

+4
1

, . , :

func discardingResult<T, U>(_ f: @escaping (T) -> U) -> (T) -> Void {
  return { x in _ = f(x) }
}

let g = f(5)
g(3)  // warns
let h = discardingResult(g)
h(4)  // doesn't warn
+5

Source: https://habr.com/ru/post/1655887/


All Articles