How to correctly use short Swift closures in calls to ObjC classes

101 views Asked by At

I want to use short form of closure {$0 > 1} in calls to NSIndexSet class:

let indexSet: NSIndexSet = getSomeIndexSet()
let filteredIndexSet = indexSet.indexesPassingTest(){$0 > 1}

but it gives me

Cannot invoke 'indexesPassingTest' with an argument list of type '((_) -> _)'

but this works: indexSet.indexesPassingTest(){(i,s) in i > 1} though type names are still not there.

Is it a bug or am I missing something?

1

There are 1 answers

5
Sandeep On BEST ANSWER

The error message says what you are doing wrong. The argument passed to block are not two different argument rather a single argument which is tuple. So, you will have to access each element in from the tuple.

Based on the comment by Martin R, it seems like closure must match the 2 arguments. So, one can use $0, or $1 or if only one is used then $0 becomes tuple.

let filteredIndexSet = indexSet.indexesPassingTest { $0.0 > 20 }

The $0.0 means the first item in the tuple which is index.