Reputation: 119
I am learning Swift and I got problem with understanding how functions work. Let's say I got a simple function:
func sayHello() {
println("hello there")
}
And I can assign this function to variable or constant in that way:
var hello = sayHello
So now variable hello is type of function which can be written in that way:
var hello:() -> () = sayHello
And now I can run/execute (is it a proper wording?) sayHello function by typing:
hello()
which prints my output "hello there"
The question is whats the difference between this:
var hello1 = sayHello()
hello1 // it prints out hello there string
and that:
var hello2 = sayHello
hello2() // it prints out hello there string as well
Upvotes: 1
Views: 195
Reputation: 40624
In a nutshell,
hello1
is the result of the execution of sayHello
. But because your function does not return anything, its value will be a Void
.
hello2
on the other hand is a reference to the function sayHello
. It is of type () -> ()
. That's why you need to execute it (the trailing '()' in your example) to get the result.
This is what we call First Class Function. One of the characteristics is that functions can be passed around and used like a variable.
Upvotes: 3