Swift Any Difference Between Closures and First-Class Functions

Swift any difference between Closures and First-Class Functions?

These notions are orthogonal. They are not directly related; they are two facts about functions in Swift.

  • Functions are first-class. This means they can be passed around — assigned as variables, passed into function parameters as arguments, and passed out of functions as results.

  • Functions are closures. This means that, at the point of definition, they capture the environment referred to inside the function body but declared outside the function body.

Here is an example (from a playground):

func multiplierMaker(i:Int) -> (Int) -> (Int) {
func multiplier(ii:Int) -> (Int) {
return ii*i
}
return multiplier
}
let g = multiplierMaker(10)
g(2) // 20

Think about the function multiplier:

  • The fact that multiplier can be returned as the result of the function multiplierMaker, and assigned to g, and that it has a well-defined type (Int) -> (Int), is because functions are first-class.

  • The fact that, when 10 is passed into multiplierMaker, the resulting multiplier function multiplies its parameter by 10, even when assigned to g and called later, is because functions are closures.

(Notice that this has nothing to do with anonymous functions. All answers or statements leading you to believe that closures have to do with anonymous functions are wrong. There are no anonymous functions in this example. An anonymous function is a closure, but only because all functions are closures.)

What is the difference between Swift Closures, Java Closures, and Python Lambda expressions?

A closure is a function that is defined in a way that allows it to carry values defined from another context, usually one of a "higher" scope.

The example you give above in Java is one. In Python, a lambda expression is not a closure. In Python, we would create a closure much like the Java example in your post. Here's an example of a Python closure:

def greet_boss(name):
def greet(person):
if person == name:
return "Yes sir!"
return f"Hello {name}"
return greet

greet_boss encloses greet and returns a function. Thus, you can do something like this: greet_boss("Obama")("Biden") and get "Hello Biden." But if you do greet_boss("Obama")("Obama") you get "Yes sir!".

Swift closures are also like that.

In Python, a lambda expression is an anonymous function. Lambda expressions define a callable, which works like a function, but it doesn't have a name. In Python, it is preferred only to use lambda expressions as parameters to higher order functions, like map and filter and other functions that take a callable as a parameter. Otherwise, you should probably just use a one line def func....

In functional programming languages functions are "first class citizens." This means that they can be passed around just like data (integers, strings, arrays, etc.) Not all languages treat functions this way. Some languages that are not strictly functional (e.g., Python) still have first class functions.
In the above examples, functions are returned by other functions: the return functions are closures. You can also pass functions as parameter values when they are first class. Example:

def return_certain_times(list_of_times, time_filter):
out = []
for time in list_of_times:
if time_filter(time):
out.append(time)
return out

If you have a list of days of the week, you can do something like return_certain_time(my_times, lambda x: x == "Saturday') and this would return a list of all the times that matched "Saturday". (This in not a great example of a function you would want, but it illustrates the concept pretty well.)

Difference between Closure Functions and Functions

Closure:

  • Closure is a block of code, treat it like an unnamed function.
  • When a closure is passed as an argument, the closure is not evaluated till the code inside the function invokes the argument.

Auto closure:

  • Auto closure is just a closure which packages the parameter values along with it.
  • When you define an autoclosure, there would be no parameters to the closure.

Difference between fCheckGender and cCheckGender:

  • fCheckGender takes a String value as an argument.
  • cCheckGender takes closure as an argument.
  • When cCheckGender is invoked, the closure is passed an argument, at this point, the closure is only passed as an argument, the closure is not executed. Only when the closure parameter is used inside the function, the closure gets executed.

The example you have stated might not be the best one to demonstrate the difference.

Let's consider a different example:

Example:

func add(a: Int, b: Int) -> Int {

print("add")

return a + b
}

func f1(pValue: Int) {

print("f1")

print("value = \(pValue)")
}

func f2(pClosure: (Int, Int) -> Int, pA: Int, pB: Int) {

print("f2")

let value = pClosure(pA, pB)

print("value = \(value)")
}

//In autoclosure the closure always takes no parameters, because the closure is packaged with parameter values while invoking
func f3(pClosure: @autoclosure () -> Int) {

print("f3")

let value = pClosure()

print("value = \(value)")
}

f1(pValue: add(a: 10, b: 20))
print("=====================\n")

f2(pClosure: add, pA: 10, pB: 20)
print("=====================\n")

f3(pClosure: add(a: 10, b: 20))
print("=====================\n")

Output:

add
f1
value = 30
=====================

f2
add
value = 30
=====================

f3
add
value = 30
=====================

Explanation of example:

  • In the function f1 pValue is an Int value.
  • So when f1 is invoked, the add is evaluated
  • In the functions f2 and f3 pClosure is a closure.
  • pClosure (closure) is not evaluated till it is invoked inside the function.

Note:

  • Focus on f3 first which accepts a closure as the argument.
  • Once you fully understand f3, then examine f2.
  • Auto closure captures the parameter values when it is invoked and later uses it.

Why and when do we need to pass a closure instead of a value:

  • There might be a scenario, where you would like to defer the execution of add till the time the function f2 invokes it.
  • There might be a scenario, where you make an asynchronous request and you want a piece of code to execute when the request completes. In this case you might pass a closure. (Closure need not always return a value, it is an unnamed function, so it can accept parameters)

Why and when do we need to an autoclosure:

  • When you want to defer the execution of add and also capture the value of it's parameters.

Suggestion:

  • Though time consuming, it is best for you to go through the Swift documentation from the beginning to fully understand it.

Reference:

As Hamish has pointed please read about closures, then auto closures from https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

Differrence between closure and function as argument in swift

In swift there really isn't any difference between functions and closures. A closure is an anonymous function (A function with no name.) That's about it, other than the syntax differences you noted.

In Objective-C functions and blocks/closures ARE different.

What is the difference between functions and closures?

Functions are, in fact, just named closures. The following are at least conceptually equivalent:

let foo = { println("hello") }

func foo()->(){ println("hello") }

This gets a little more complicated in the case of using func to declare methods, as there's some interesting bits of sugar added regarding the automatic insertion of public named parameters, etc. func myMethod(foo:Int, bar:Int, baz:Int) becomes func myMethod(foo:Int, #bar:Int, #baz:Int), for example.

But it's still true that even methods are just a specific case of closures, and if it's true of closures, it's true of functions and methods as well.

What is the difference between swift variable and function when use closure in variable?

A variable holds/references a value; a function is a value. Thus variables can hold/reference numbers, strings, instances and, in some languages, functions. Languages that allow variables to hold/reference functions are languages with 'first class functions'

The advantage of closures is that they 'capture' values in their 'lexical scope'. For example, say you need a callback function that executes when some computation completes. You want the callback to dismiss a view controller and log some information:

class MyViewController : ViewController {
func takeAction (message:String) {
// do some stuff, then
doComputation {
self.dismissViewController()
NSLog ("took action: \(message)")
}
}
}

In the above, the argument to doComputation is a closure; it captures the values bound to self and message from the closure's lexical environment.

Is Javascript closures and Swift closures are same

In practice, yes.

The base difference is that in Swift closure is a reference type. So, you have to be aware of using strong references for income captured variables.



Related Topics



Leave a reply



Submit