First Class functions in Swift

Swift has first-class functions. First-class functions can be

  1. Stored into variable

  2. Returned from a function

  3. Passed as an argument

Returning a function from another function and storing them in a variable

func add(p1: Int, p2: Int) -> Int {

return p1+p2

}

func subtract(p1: Int, p2: Int) -> Int {

return p1-p2

}

func multiply(p1: Int, p2: Int) -> Int {

return p1*p2

}

func divide(p1: Int, p2: Int) -> Int {

return p1/p2

}

func mod(p1: Int, p2: Int) -> Int {

return p1%p2

}

The above code is refactored to below where functions are returned from another function and functions are stored in a variable.

enum Operation {

case add

case subtract

case multiply

case divide

case mod

}

func chooseOperator(operation: Operation) -> (Int, Int) -> Int {

func add(p1: Int, p2: Int) -> Int {

return p1+p2

}

func subtract(p1: Int, p2: Int) -> Int {

return p1-p2

}

func multiply(p1: Int, p2: Int) -> Int {

return p1*p2

}

func divide(p1: Int, p2: Int) -> Int {

return p1/p2

}

func mod(p1: Int, p2: Int) -> Int {

return p1%p2

}

switch operation {

case .add:

return add

case .divide:

return divide

case .mod:

return mod

case .multiply:

return multiply

case .subtract:

return subtract

}

}

let addition = chooseOperator(operation: .add)

addition(1, 2)

let multiplication = chooseOperator(operation: .multiply)

multiplication(3, 2)