Search code examples
swiftswift3

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


Solution

  • 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.