- Mastering macOS Programming
- Stuart Grimshaw
- 199字
- 2021-07-02 22:54:32
Closures that take arguments
A higher order function may require a closure that takes an argument itself, and/or returns a value:
func processInt(f: (Int) ->Int )
{
let x = f(42)
// do something with x
print(x)
}
This function takes a closure of type (Int) -> Int. Having defined a type alias, we could have used that instead:
func processInt(f:SingleIntegerOperation)
{
let x = f(42)
// do something with x
print(x)
}
The processInt function doesn't know whether the SingleIntegerOperation that it is passed will print an Int, or use it to make an HTTP request, or whatever. It will simply supply that closure with an argument (in this case 42).
So, we could pass the following closure:
{x in return x / 2}
This is the same as if we had defined a function:
func nameless(x: Int) -> Int {
return x / 2
}
We can pass this closure to the processInt function:
processInt(f: {x in return x / 2})
What processInt does with the result of that closure is its own business; the closure itself, and indeed the code that passes that closure to processInt, knows nothing of the context in which it is called.