[Request] Variadic parameters as arguments in closures


(Ramon Gilabert) #1

Hello everybody,

This is my first request or suggestion, so don’t really know if this is the format you are looking for. I’ve been searching lately to build the perfect API for a soon to be open source project.

Such project has a different set of functions that have different views as parameters, based on the number of views, the closure that the function will give back to you will have different arguments, (one view returns one argument in the closure). After putting a variadic argument I wanted to do the same for closures since the API reads much nicer and I don’t have to duplicate code to cover all the cases.

From a code point of view it makes sense that it behaves like that, you have a variadic parameter and inside the function it behaves as an array, the same way, you have different variadic parameters in the closure and inside such implementation you have an array. Even though this is nice, I think the best case scenario to not have to repeat code would be to parse in the compiler in a smart way, meaning, if the argument is a variadic component, then $0 will be the first argument of the variadic array, $1 the second one and so on.

This way API’s like:

https://github.com/robb/Cartography/blob/master/Cartography/Constrain.swift

Could be simplified into just one method with variadic functions without having the user to deal with an array in their end.

Going to attach a bit of code from the Apple documentation, retouched a bit: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

func divideTwo(numbers: Double…, solutions: (Double…) -> Void) {
  var results: [Double] = []
  for number in numbers {
results.append(number / 2)
  }
	
    solutions(results)
}

  // In their end.
 
  divideTwo(2, 4) {
    print($0)
    print($1)
  }

This would only behave like this in the case where a variadic argument is given back as a parameter in the closure.