arrays - How to forward functions with variadic parameters? -


in swift, how convert array tuple?

the issue came because trying call function takes variable number of arguments inside function takes variable number of arguments.

// function 1 func sumof(numbers: int...) -> int {     var sum = 0     number in numbers {         sum += number     }     return sum } // example usage sumof(2, 5, 1)  // function 2 func averageof(numbers: int...) -> int {     return sumof(numbers) / numbers.count } 

this averageof implementation seemed reasonable me, not compile. gives following error when try call sumof(numbers):

could not find overload '__converstion' accepts supplied arguments 

inside averageof, numbers has type int[]. believe sumof expecting tuple rather array.

thus, in swift, how convert array tuple?

this has nothing tuples. anyway, isn't possible convert array tuple in general case, arrays can have length, , arity of tuple must known @ compile time.

however, can solve problem providing overloads:

// function actual work func sumof(_ numbers: [int]) -> int {     return numbers.reduce(0, +) // functional style reduce }  // overload allows variadic notation , // forwards args function above func sumof(_ numbers: int...) -> int {     return sumof(numbers) }  sumof(2, 5, 1)  func averageof(_ numbers: int...) -> int {     // calls first function directly     return sumof(numbers) / numbers.count }  averageof(2, 5, 1) 

maybe there better way (e.g., scala uses special type ascription avoid needing overload; write in scala sumof(numbers: _*) within averageof without defining 2 functions), haven't found in docs.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -