print
and return
perform two very different functions. print
, of course, prints out the given data to the debugging console. return
indicates that a func
should exit. Sometimes return
returns something, like in return 0
or whatever, but other times it exits without passing any data back to the code that called the func
.
let driving3 = {
print("I'm driving in my car")
}
func travel(action: () -> Void) {
print("I'm getting ready to go.")
action()
print("I arrived!")
}
travel(action: driving3)
In this example, the return type is Void
, meaning this is one of those functions (actually a closure here, which is basically an anonymous function) that doesn't return anything. So we don't need to worry about return
here at all. The type signature () -> Void
just means we want a closure that take no parameters and returns no result.
So what happens is that you define a closure (a.k.a. anonymous function) and store it in the constant driving3
. This closure matches the type signature () -> Void
that we are expecting in the travel(action:)
function. Then when you then pass driving3
into the travel(action:)
function, it gets assigned to the action
parameter. When you append ()
to action
, this has the effect of calling the closure stored inside and whatever code it contains is executed. In this case, it's the statement print("I'm driving in my car")
. Essentially, then, the code does this:
func travel(action: () -> Void) {
print("I'm getting ready to go.")
print("I'm driving in my car") // <-- because this is what was passed in from driving3 to the action parameter
print("I arrived!")
}
Make sense?