From the course: Learning Higher-Order Functions with Swift

Functions are closures

From the course: Learning Higher-Order Functions with Swift

Start my 1-month free trial

Functions are closures

- [Instructor] So now that we have a pretty good idea of what closures are, let's talk a little bit about functions. Well, we're still talking about closures 'cause functions are named closures. That's right. So if you know what a function is just take away the name and you pretty much have a closure and vice versa. So let's look at some examples. So here we have a closure and a function. Notice that they both have two parameters, val one and val two. They both have types for those parameters, ints. They both have a return type of an int, and they both return the sum of those two. Now the syntax is a little bit different, and again functions are named closures so this function has a name. But for the most part they do the same thing. Take two ints, add 'em together, return the sum. The difference is is this closure's a little bit easier to pass around as it's defined here, whereas this function over here, you don't typically pass that around to anything. And we'll see other ways of doing this but we just kind of want to see the similarities and differences for now. So again, what are functions? We talked about closures, but what are functions? Well, global and nested functions, as introduced in functions from this documentation, are actually special cases of closures. Closures take one of three forms. Global functions. This is what we're used to. These are closures that have a name and do not capture any values, so nothing within the scope at that time. Nested functions are closures that have a name and are captured values from their enclosing function. So these are functions that are defined within other functions. Not too common in my experience. Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context. That's what we talked about in the previous video. So again, global functions are closures that have a name. Nested functions we don't deal with too much. And then there's regular closures. So again, functions are just named closures. They don't capture their scope. But other than that, they're pretty much the same thing. So from that point on we can treat them pretty similarly. And again, this is where we're going to start with these understandings of closures and functions. Once we start thinking of them in a little bit different terms, we start seeing the power of what we can do for them. And that's where we're going.

Contents