DEV Community

Cover image for Day 7 of 100 Days of SwiftUI

Day 7 of 100 Days of SwiftUI

ramsescabello profile image Ramsés Cabello⚡️ ・1 min read


Closures are really challenging. Still trying to understand how they can be used and what wrapping my head around the syntax.

In addition to the content on the Day 6 and 7 around Closures, I've been checking out other tutorials online.

Specially this tutorial was pretty useful:

So far, here's my notes on Day 7.

Closures as…


Closures that use parameters behave as a sealed box.

Parameters returning values

Instead of using () -> Void meaning that it accepts no parameters and return nothing, we could actually specify a DataType to be expected as a return.

Shorthand parameter names

Swift has a shorthand that lets you remove the parameter and the expected return datatype by using a shorthand:

travel {
    print("Something \($0)"
Enter fullscreen mode Exit fullscreen mode

The shorthand is a dollar sign with a number starting from 0. Shorthands are not useful in the following situations:

  • Comparing parameters.
  • If you’re repeating $0 many times, maybe it is better to give the parameters a name.

Closure summary

  1. You can assign closures to variables, then call them later on.
  2. Closures can accept parameters and return values, like regular functions.
  3. You can pass closures into functions as parameters, and those closures can have parameters of their own and a return value.
  4. If the last parameter to your function is a closure, you can use trailing closure syntax.
  5. Swift automatically provides shorthand parameter like $0 and $1, but not everyone uses them.
  6. If you use external values inside your closures, they will be captured so the closure can refer to them later.


Editor guide