Ray Tso
Ray Tso

Reputation: 566

Function type vs functions (methods)

I was studying Swift when I came across this:

var action: () -> Void = {
    print "hi"
}   
var someVariable: Int -> Int

As I know so far that these should be function-type variables which "action" is a "takes no parameters and returns nothing"-type while "someVariable" is a "takes an Int and returns an Int"-type.

So my question is: Why not just use func?

func action() {
    print "hi"
}
func someVariable(a: Int) -> Int {
    return a + 1
}

Are these two the same thing? Or is there some preference when writing code to use func over function-type variables or vice-versa? If there is, when to use what?

Upvotes: 1

Views: 200

Answers (2)

fpg1503
fpg1503

Reputation: 7582

Functions are a special case of Closures. As per the Swift docs:

Global functions are closures that have a name and do not capture any values.

Nested functions are closures that have a name and can capture values from their enclosing function. Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context. Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-free syntax in common scenarios.

Being a special case of closures, functions can be used anywhere a closure is required.

Upvotes: 1

Strat Aguilar
Strat Aguilar

Reputation: 828

In the case of:

var someVariable: Int -> Int 

You're declaring a variable with a method signature accepting an Int and returning an Int. You can assign any function that complies with this method signature. You can pass this variable around and assign it like any other variable when necessary. It adds flexibility as to how you can assign your methods.

Upvotes: 4

Related Questions