How to return the sum of functions in Swift? -


func studiotrackingcost(studiotrackingdays: int, studiotrackingrate: double) -> double {     return double(studiotrackingdays) * studiotrackingrate }  func studiooverdubcost(studiooverdubdays: int, studiooverdubrate: double) -> double {     return double(studiooverdubdays) * studiooverdubrate }  func studiomixingcost(studiomixingdays: int, studiomixingrate: double) -> double {     return double(studiomixingdays) * studiomixingrate } 

not sure looking for, if want define function receives 6 params , returns sum of results of 3 functions then...

func tot(     studiotrackingdays: int, studiotrackingrate: double,     studiooverdubdays: int, studiooverdubrate: double,     studiomixingdays: int, studiomixingrate: double     ) -> double {     return         studiotrackingcost(studiotrackingdays, studiotrackingrate: studiotrackingrate) +         studiooverdubcost(studiooverdubdays, studiooverdubrate: studiooverdubrate) +         studiomixingcost(studiomixingdays, studiomixingrate: studiomixingrate)  } 

let's go crazy

let's define type alias parameters accepted functions

typealias paramtype = (int, double) 

and type alias represents functions

typealias functiontype = paramtype -> double 

now can define function tot accepts list of tuples, every tuple element of type functiontype , of type paramtype.

func tot(elms: (logic: functiontype, params: paramtype)...) -> double {     return elms.reduce(0) { (res, elm) -> double in         return elm.logic(elm.params)     } } 

finally can invoke tot passing variable number of params this

tot(     (logic: studiotrackingcost, params: (1,2)),     (logic: studiooverdubcost, params: (3,4)),     (logic: studiomixingcost, params: (5,6)) ) 

or this

tot(     (logic: studiotrackingcost, params: (1,2)),     (logic: studiooverdubcost, params: (3,4)) ) 

or this

tot((logic: studiotrackingcost, params: (1,2))) 

Comments