Closure in Swift 5

Learn by examples what is Closure and how to use it in your code

Amr Omran
The Startup
2 min readMay 11, 2020

--

credits pixabay.com

What is Closure?

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

swift.org

  • Closure is a function and “func” keyword
  • Closure is a block of code that you can assign to a variable.
  • In Swift Variables “var” and Constants “let” store information, Functions “func” execute tasks and Closures have a function code in form of a variable and can be passed around.

What are the types of the Closure?

  • Closure without niether parameters nor return value.
  • Closure that accepts parameters.
  • Closure returns value.
  • Trailing Closure

Closure without parameters or return value

Closure that acceptes parameters

Since closures parameters don’t have names you can refer to them with $ + parameters number

Closure that returns values

closures can also accept parameters and return value

Trailing Closure

If the last parameter to a function is closure that’s called trailing closure

Another example of the trailing closure with parameter

Trailing closure with parameter and returns value

--

--