Anonymous closure can not be used inside a closure that has explicit arguments
There are two ways to write closures: with explicit argument names, or by referring to the arguments as $0, $1 etc.
For example, these two things are equivalent:
// implicit argument names, $0 and $1
let x = reduce(1...5, 0) { $0 + $1 }
// explicit argument names i and j
let y = reduce(1...5, 0) { i, j in i + j }
But you can’t mix these things – either you name the arguments, or you use $n
. You can’t do both:
// name the arguments, but still use $0 and $1
let x = reduce(1...5, 0) { $0 + $1 }
// compiler error: Anonymous closure arguments cannot be used
// inside a closure that has explicit arguments
In your example, it looks like you’ve forgotten to supply a closure to the filter
method. This means your $0
isn’t inside a new closure without arguments – so the Swift compiler thinks your $0
is referring to the outer closure that names it’s arguments explicitly as records
and error
. So it’s complaining you can’t refer to arguments as $0
inside a closure with explicit argument names.
(the fix is of course to actually supply a closure to filter
i.e. replace your ()
with {}
)
I was getting this error for a totally different reason.
I was returning a closure instead of an array.
I was doing
return { cars.map {...}}
Removing the extra curly braces fixed it. All I did to fix it was:
return cars.map {...}