First class citizen

 In Swift, functions are considered first-class citizens. This means that functions are treated as values that can be assigned to variables, passed as arguments to other functions, and returned as values from functions. 

For example, you can define a function and assign it to a variable:

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

let myFunc = add

Here, the add function is assigned to the myFunc variable, which means you can call myFunc just like you would call add:

let result = myFunc(2, 3)  // result = 5

You can also pass functions as arguments to other functions:

func applyFunction(_ a: Int, _ b: Int, _ f: (Int, Int) -> Int) -> Int {
    return f(a, b)
}

let result = applyFunction(2, 3, add)   // result = 5

Here, the applyFunction takes a function as its third argument, and you can pass in the add function to apply it to the first two arguments. 

In Swift, first-class functions enable powerful functional programming constructs like higher-order functions and closures.

Comments

Popular Posts