Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical sign as function parameter

Tags:

swift

Can I somehow send the mathematical sign (+, -, *) as function parameters? I want to call reduce() function for different sign.

like image 763
Nikita Ermolenko Avatar asked Dec 28 '15 15:12

Nikita Ermolenko


1 Answers

In swift signs are functions name for a specified mathematic operation. To pass sign as parameter the parameter type must be function that takes two numbers and return a number. If you command + click on any sign you will see its definition as follow :

public func +(lhs: UInt8, rhs: UInt8) -> UInt8

public func +(lhs: Int8, rhs: Int8) -> Int8

public func +(lhs: UInt16, rhs: UInt16) -> UInt16

public func +(lhs: Int16, rhs: Int16) -> Int16

public func +(lhs: UInt32, rhs: UInt32) -> UInt32

public func +(lhs: Int32, rhs: Int32) -> Int32

public func +(lhs: UInt64, rhs: UInt64) -> UInt64

public func +(lhs: Int64, rhs: Int64) -> Int64

public func +(lhs: UInt, rhs: UInt) -> UInt

public func +(lhs: Int, rhs: Int) -> Int

In your case your reduce function should look as the following one

func reduce(sign: (Int,Int)->Int) -> Int{

    return sign(2,3)
}

reduce(*)
reduce(-)
like image 155
Zell B. Avatar answered Sep 19 '22 01:09

Zell B.