Chris Hutchison
Chris Hutchison

Reputation: 611

Is it possible to declare an empty function as a variable in Swift?

Is it possible to do something like this, and create an empty function that will later be assignable, because I keep getting an error where i can't call the function that was assigned this is the closest I have gotten

fileprivate class actionButton: UIButton{
    var functo = ()
    func tapped(functoCall: () ->Void){
        self.functo()
    }
}

this buttons initialized in a function which takes a function as a parameter and passes it on to this button which is a descendent of the class specified above

    button.functo = funcToCall()
    button.addTarget(self, action: #selector(yes.tapped(functoCall:)), for: .touchDown)

the issue i get is when i try to call self.functo() i get cannot call non-function type

Upvotes: 2

Views: 5877

Answers (2)

Md Abir Hossain
Md Abir Hossain

Reputation: 1

Don't know this is going to help you. But I think SwiftUI user's will be helped. You can declare like this

var functo: () -> Void

If you want to use it in SwiftUI you can pass function from one view to another view like this

struct CustomAlertView: View {
    var title: String
    var msg: String

    // Function for execution
    var functo: () -> Void

    var body: some View {
        VStack {
            Text(title)
                .font(.title.weight(.semibold))
                .padding(10)
            
            Text(msg)
                .font(.title3.weight(.medium))
        }
    }
}

And you can pass function from other View to that view in parameter like this

struct NewView: View {
    var body: some View {
        VStack {
            CustomAlertView(functo: timeTravel)
        }
    }

    func timeTravel() {
        print("Do something")
    }
}

Note: If you want to use it as a real alert, use it in ZStack.

Upvotes: 0

Thomas Krajacic
Thomas Krajacic

Reputation: 2747

Yes that is possible.

The reason you are getting the error is that the compiler can't know that functo is in fact a function that is callable. You made it an Any implicitly.

You just have to cast it (using if let for example) to a function of the desired type first.

Something like this should get you started:

var myfunc: Any = ()

func test() -> String {
    return "Cool"
}
// Assign any function to myfunc
myfunc = test

// Just cast it to the expected type
if let x = myfunc as? ()->String {
    x()
}

In case the question is just particular to this problem (as a downvoter thinks) you can just type your variable with the signature of your function. This is the trivial case:

var myfunc: ((Any) -> Void)? = nil

Then it is callable when you assign it.

Upvotes: 1

Related Questions