UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 6 Closures Part One

Forums > 100 Days of SwiftUI

Hi guys,

Can someone help me to understand closures as parameters? I dont quite understand the syntax .

let driving = { print("I'm driving in my car") }

func travel(action: () -> Void) { print("I'm getting ready to go.") action() print("I arrived!") }

travel(action: driving)

I'm getting ready to go. I'm driving in my car I arrived!**

Why and when do I need to use 'action()'? I'm very confused with the print action in "func travel" especially. Thanks guys

3      

So action is the parameter to the travel function. It's a closure of type () -> Void. It can be referred to within the travel function using the name action. In order to call (execute) the closure passed in the parameter, you have to use its name followed by parentheses.

So within the travel function:

  • action is a reference to the closure passed as a parameter
  • action() calls (executes) the closure passed as a parameter

4      

Hi @VicLee92

I think most people struggle with closure and in the words of Paul

Don’t despair. Sometimes fighting to learn something makes it stick in your head better – there is no learning without struggle!

As @roosterboy is correct what he say but you have to get it in your mind.

What I would suggest is go over the tutorial again but you will be using them alot in the future and more you use them the more clear the get.

You have a basic closures that is effectively creates a function without a name

let driving = {
    print("I'm driving in my car")
}

This () -> Void mean that you can pass in a function

func travel(method: () -> Void) { // <- pass in a function or closure
    print("I'm getting ready to go.")
    method() // <- this is where the function will be called
    print("I arrived!")
}

so now when you 'run' the travelfunction you have to pass in a function which in this case is driving

travel(method: driving)

PS change the action to method to show that the parameter name is a hint on what should be passed into function.

Nigel

4      

@NigelGee

Thank you for this explanation. You've just helped me a lot!

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.