具有显式参数的闭包内部不能使用匿名闭包 [英] Anonymous closure can not be used inside a closure that has explicit arguments

查看:120
本文介绍了具有显式参数的闭包内部不能使用匿名闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

smb可以解释什么问题吗,应该如何修改代码?

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

我需要过滤 CKRecord s从 CloudKit 返回。

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 {

        }
    })

推荐答案

编写闭包的方法有两种:使用显式参数名称,或将参数称为$ 0, $ 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 }

但是您不能混合使用这些东西–您可以命名参数,或者使用 $ n 。您不能同时做这两个事情:

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

在您的示例中,您似乎忘记了为过滤器提供闭包方法。这意味着您的 $ 0 不在没有参数的新闭包中–因此Swift编译器认为您的 $ 0 是指外部闭包将其参数明确命名为记录错误。因此,它抱怨您不能在带有显式参数名称的闭包内将参数称为 $ 0

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.

(当然,修复程序实际上是提供 filter 的闭包,即用替换您的() { }

(the fix is of course to actually supply a closure to filter i.e. replace your () with {})

这篇关于具有显式参数的闭包内部不能使用匿名闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆