Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“Functions are a first-class type” in swift?

the little knowledge , I have about first class function is that it supports passing functions as arguments and we can also return them as the values in another function ... I am very new in Swift programming language can anyone please elaborate it with an example.

like image 858
Anurag Bhakuni Avatar asked Oct 07 '14 12:10

Anurag Bhakuni


2 Answers

A very simple example to demonstrate this behaviour:

func functionA() {
    println("Hello by functionA")
}

func executeFunction(function: () -> ()) {
    function()
}

executeFunction(functionA)
like image 128
Kirsteins Avatar answered Nov 25 '22 16:11

Kirsteins


First-Class functions are functions that can return another functions. For instance:

func operate( operand: String) -> ((Double, Double) -> Double)?{

    func add(a: Double, b: Double) -> Double {
        return a + b
    }

    func min(a: Double, b: Double) -> Double{
        return a - b
    }

    func multi(a: Double, b: Double) -> Double {
        return a * b
    }

    func div (a: Double, b: Double) -> Double{
        return a / b
    }

    switch operand{
    case "+":
        return add
    case "-":
        return min
    case "*":
        return multi
    case "/":
        return div
    default:
        return nil
    }
}

The function operate returns a function that takes two double as its arguments and returns one double.

The usage of this function is:

var function = operate("+")
print(" 3 + 4 = \(function!(3,4))")

function = operate("-")
print(" 3 - 4 = \(function!(3,4))")

function = operate("*")
print(" 3 * 4 = \(function!(3,4))")

function = operate("/")
print(" 3 / 4 = \(function!(3,4))")

When you don't care about the implementation of a function, using First-Class functions to return these functions become beneficials. Plus, sometimes, you are not responsible to develop (or not authorised ) of the functions like add, min. So someone would develop a First-Class function to you that returns these functions and it is your responsibility to continue ....

like image 25
William Kinaan Avatar answered Nov 25 '22 15:11

William Kinaan