How to take in closures as parameters in custom SwiftUI Views
You most definitely have had to deal with closures in SwiftUI such as a Button with action. Today you will learn how to require a closure in the parameters of your own custom views.
@State var myFunc:(() -> Void)
In order for any variable to be considered a parameter we need to use the @State property first, then we create a variable that has a function type of whatever type you wish, in this case I chose void, however you can chose to use whatever type you wish. In these closures you can also set parameters for your closure like this.
@State var myFunc:((_ id:Int) -> Void)
As you see we added a parameter to our closure called id, you can reference this variable in your closure like this.
ContentView(myFunc: {id in
//Do stuff in your closure
}
)
ContentView(myFunc: {id in
print("id: \(id)")
}
)
Closures will be your best friend when customizing your own views. For example you could take in a closure that returns a AnyView type, and have a easy way to add a view to your custom view that can be provided by the user of that view. This is useful for dynamic views that have lots of moving parts.