Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous closure can not be used inside a closure that has explicit arguments

Can smb explain what is the problem, how should I modify my code?

I need to filter CKRecords returned from CloudKit.

override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {

    let defaultContainer = CKContainer.defaultContainer()
    let publicDatabase = defaultContainer.publicCloudDatabase

    let myfunc2 = myfunc(names, { (records: [CKRecord], error: NSError) in
        if error == nil {

            let records2 = records.filter($0.value > sourceIndexPath.row && $0.value < destinationIndexPath.row)

            let mro = CKModifyRecordsOperation(recordsToSave: [], recordIDsToDelete: [])

        } else {

        }
    })

enter image description here

like image 858
János Avatar asked Dec 11 '14 22:12

János


2 Answers

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 {})

like image 80
Airspeed Velocity Avatar answered Nov 08 '22 17:11

Airspeed Velocity


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 {...}
like image 41
mfaani Avatar answered Nov 08 '22 17:11

mfaani