Function Type
Note
Open Functional.playground
at the Introduction
page.
First, let's reiterate what a function type is:
var sum: (Int, Int) -> Int
The type of sum
is a function that takes two Int
values and returns one Int
value. We can assign both functions and closures to it, as they are essentially the same thing:
func sumFunction(a: Int, b: Int) -> Int { return a + b } let sumClosure = {(a: Int, b: Int) in return a + b} sum = sumFunction sum = sumClosure
We can also assign an operator to it:
sum = (+)
This is because an operator is a function (the parentheses around the + operator are just to signal that we want to use it as a function, not add things together right away). The definition of the +
operator for Int
is:
static func +(lhs: Int, rhs: Int) ...
Get Beginning Swift now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.