reza23
reza23

Reputation: 3385

Passing a function to a class in Swift

I want to pass a function to a class and then call it from the class. Here is my code:

class TestClass {
    var action:()

    init( action:())
    {
        self.action = action
    }
}

func doSomething()
{
    println("need to do something")
}


let testingFunction = TestClass(action:doSomething())
testingFunction.action

When I call testingFunction.action nothing happens. Any suggestion.

Upvotes: 1

Views: 1810

Answers (1)

nickgraef
nickgraef

Reputation: 2417

A function type contains the parameter types and the return type. In this case, doSomething has a function type of () -> Void. Void is an empty tuple, so this is equivalent to () -> (). So your TestClass would look like this:

class TestClass {
    var action: () -> Void
    init(action: () -> Void) {
        self.action = action
    }
}

To pass a function as a parameter, simply use the name of the function just like the name of any other variable. So you would initialize TestClass like this:

let testingFunction = TestClass(action: doSomething)

and call the action function like this:

testingFunction.action()

See the Swift Language Guide section on function types for more information.

Upvotes: 3

Related Questions