Mar 31 2020

Using closures as function parameters.


When you have a function, it could be that you would want to run some code after the function finished based on what was done by the function. In that case, you can have a closure as a parameter for a function that will run when you call it in your function. Or, what is a more common situation is that you have a function, that doesn’t change on behalf of the state of the app, and you want to run some extra code on specific places in your codebase. In that case, you could use closures.


If you have a function that prints out the time and date of the app at the state the function was called, and one place in your codebase you also want the location. If you call that function in more places, then it is more useful to let it accept a closure optionally that to create a separate function for that one use case.

So, you would use closures as a parameter for a function as follows:

func printDateAndTime(closure: (String) -> ()) {
    print("The Time is (currentTime) and the date is (currentDate)")

What That does is the following, you define a parameter that is of type (String) -> () which says that the parameter is a closure that accepts one parameter of type String and returns a function. You can also add more parameters for the function as you would for a regular function. ie closure: (String, Int) ->() or none by just deleting the string keyword.

You would call that function as follows:

printDateAndTime { (location: String) in
    print("The location is \(location)")

In our case, I want to print out the location of the user. So, instead of the parentheses of the function call, you start the closure right away. So we add a parameter of type String as we set inside the function parameters and in the closure we use a print statement which is a function.

Note: You can see that there is no return keyword even though we have specified the closure as returning a function. This is because swift has something called shorthand code that lets you shorten your code by, like in our case, not having to write a return keyword in a one-line expression. You can see in more situations shorthand code, but that is maybe for another article.

When you run that code, this is what is being printed out in the console:

"The Time is (currentTime) and the date is (currentDate)"
"The location in myLocation"

I hope you enjoyed this article and I hope that it will help you in your own code.

Don’t forget that you can email me at for any questions, feedback or if you just wanted to say hi.