How To Declare A Variable of Type Function and Pass Function To it?

Is this possible?

I have a class/struct that will store a function that will be used as an action to the button.

e.g.

struct Test {
    var action: (() -> Void)?
}

This works

tempfunc() -> Void {
    print("clicked it")
}

let test = Test()
test.action = tempfunc

Button("click me", action: test.action)

What I want to do is something like this.

test.action = () -> Void {
   print("clicked")
}

Is this possible? If i try that code, error shows up saying "Cannot assign value of type '()' to type '() -> Void'"

Answered by Claude31 in 731919022

When you write:

var clickMe = () -> Void

You assign a type to a var, that cannot work, you need to assign an instance of the Type, such as:

var clickMe : () -> Void = { }

And you should not redeclare the type when you set test.clickMe

So at the end, your code could be:

struct Test {
    var clickMe : () -> Void = { }
}
var test = Test()
test.clickMe = {
    print("clicked it")
}
Button("click me", action: test.clickMe)

To make it easier to read, defining a typealias is a good practice.

typealias SimpleClosure = () -> Void

struct Test {
    var clickMe : SimpleClosure = { }
}

var test = Test()
test.clickMe = {
    print("clicked it")
}
Button("click me", action: test.clickMe)

You can also pass a func that has the SimpleClosure signature:

func aFunc() {
    print("From func")
}
Button("click my func", action: test.clickMe)
test.clickMe = aFunc
test.clickMe()
Accepted Answer

When you write:

var clickMe = () -> Void

You assign a type to a var, that cannot work, you need to assign an instance of the Type, such as:

var clickMe : () -> Void = { }

And you should not redeclare the type when you set test.clickMe

So at the end, your code could be:

struct Test {
    var clickMe : () -> Void = { }
}
var test = Test()
test.clickMe = {
    print("clicked it")
}
Button("click me", action: test.clickMe)

To make it easier to read, defining a typealias is a good practice.

typealias SimpleClosure = () -> Void

struct Test {
    var clickMe : SimpleClosure = { }
}

var test = Test()
test.clickMe = {
    print("clicked it")
}
Button("click me", action: test.clickMe)

You can also pass a func that has the SimpleClosure signature:

func aFunc() {
    print("From func")
}
Button("click my func", action: test.clickMe)
test.clickMe = aFunc
test.clickMe()
How To Declare A Variable of Type Function and Pass Function To it?
 
 
Q