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

痞子三分冷 提交于 2019-12-08 15:40:13

问题


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 {

        }
    })


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/27433782/anonymous-closure-can-not-be-used-inside-a-closure-that-has-explicit-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!