Closures
Anonymous functions.
Closures
Anonymous functions.
0
0
Checkbox to mark video as read
Mark as read

Closures are just anonymous functions, they work the same as the functions we already know with the difference that a closure doesn't have a name. This is why we need to assign our closures to a variable.

Creating and using closures

Let's see the difference between a normal function and a closure:

func myFunction(myParameter: String, myOtherParameter: String) -> Int {
    return 12
}

var myClosure: (String, String) -> Int = { myParameter, myOtherPatameter in
    return 12
}

// Execute
let myFunctionResult: Int = myFunction(myParameter: "Hello", myOtherParameter: "World")
let myClosureResult: Int = myClosure(myParameter: "Hello", myOtherParameter: "World")

As you can see, both can execute a block of code, take one or more parameter and return a result. The advantadge of the closure is that it is stored in a variable, meaning that we can use it as a parameter as well.

When to use a closure

Let's see an example where we have a subview that we use to display a custom button. We can add a closure as a property (in this case without any parameters nor a result), so we are able to execute a block of code when the subview executes our closure.

First we create our subview with a closure as a property.

struct MyButton: View {

    let myButtonAction: () -> Void

    var body: some View {
        Button(action: {
            myButtonAction()
        }, label: {
            Text("Button")
                .padding()
                .background(.green)
                .cornerRadius(12)
        })
    }
}

Then we can pass our block of code as a parameter:

struct ContentView: View {

    var body: some View {
        MyButton(myButtonAction: {
            print("Button pressed")
        })
    }
}

course

Quiz Time!

0 Comments

Join the community to comment
Sign Up
I have an account
Be the first to comment

Accept Cookies

We use cookies to collect and analyze information on site performance and usage, in order to provide you with better service.

Check our Privacy Policy