A closure expression generally has the form
{ (param_1 : type_1, ..., param_n : type_n ) -> return_type in
statements
}
When the closure type is known, you can omit the parameter types, the return type
and also the parentheses around the parameters:
{ param_1, ..., param_n in
statements
}
So to answer your question: The in
keyword separates the parameters from the
statements, therefore in your example, number
is the (only) parameter.
Note that only (instance or class) methods use external (named) parameters, but (normal)
functions and closures do not. So it makes no difference if you write
let clo = { number in 3 * number }
let foo = clo(1) // foo = 3
or
let clo = { x in 3 * x }
let foo = clo(1) // foo = 3
and
numbers.map(clo)
applies the closure to each element of the array and returns an array of the
return values.
An implementation of map
could look like this (I took and modified the code from
https://stackoverflow.com/a/24028208/1187415):
extension Array {
func myMap<U>(transform: (T) -> U) -> U[] {
var result = U[]() // start with empty result array
for item in self { // iterate over all items of the array
let tmp = transform(item); // map this element ...
result.append(tmp) // ... and append the mapped element to the result array
}
return result
}
}
myMap
is an instance method that takes one argument of type (T) -> U
and applies it to all elements of the array itself.
A simpler example for a function (without generics) taking an integer array and a closure as arguments would be
func myMapp(array: Int[], transform:(Int)->Int) -> Int[]
{
var result = Int[]()
for item in array {
let tmp = transform(item);
result.append(tmp)
}
return result
}
Then you can do
let numbers = [1, 2, 3]
let mapped2 = myMapp(numbers, { (number) in 3 * number })