swift - Function with generic type -
i have function can calculate sum of numbers in array condition so:
func sumofarraywithcondition(array: [int], filter: (element: int) -> bool) -> int { var result = 0 in 0..<array.count filter(element: array[i]) { result += array[i] } return result } now want work int, float, double type. have tried, didn't work.
protocol addable { func +(lhs: self, rhs: self) -> self } extension int: addable {} extension double: addable {} extension float: addable {} func sumofarraywithcondition<t: addable>(array: [t], filter: (element: t) -> bool) -> t { var result = 0 in 0..<array.count filter(element: array[i]) { result += array[i] // <-------- error here } return result // <-------- error here } but says:
binary operator '+=' cannot applied operands of type 'int' , 't'
so how it.
any helps appreciated. thanks.
first issue compiler inferring type int var result because don't declare type , initialize 0. need result of type t.
first, in order initialize result instance of type t value 0, need specify addable integerliteralconvertible, true int, double , float. can declare result type t , go there.
as rob pointed out, need add += function protocol if want able use it.
so final code achieves looking is:
protocol addable : integerliteralconvertible { func +(lhs: self, rhs: self) -> self func +=(inout lhs: self, rhs: self) } extension int: addable {} extension double: addable {} extension float: addable {} func sumofarraywithcondition<t: addable>(array: [t], filter: (element: t) -> bool) -> t { var result:t = 0 in 0..<array.count filter(element: array[i]) { result += array[i] } return result }