Swift:无法使用类型'((Any)throws - > Bool)的参数列表调用'filter'

时间:2017-01-24 18:46:45

标签: ios swift filter swift3

我有一个带有一些数据的提取请求,我想过滤一下,如下所示:

// Set up fetch request 
let finalVariants : [DBVariant]
do {
  let variants = try context.fetch(request)
  finalVariants = variants.filter() { $0.variant == true }
} catch let error as NSError {
  // Handle error 
  finalVariants = []
}

编写此代码时,Xcode会在标题中给出错误:

Cannot invoke 'filter' with an argument list of type '((Any) throws -> Bool)'

过滤器块中的代码不会抛出,将过滤器块移动到带有签名的单独var(Any) - > Bool没有帮助。

1 个答案:

答案 0 :(得分:0)

答案结果是我没有解包并将类型分配给获取请求的可选结果,因此工作代码如下所示:

// Set up fetch request 
let finalVariants : [DBVariant]
do {
  let variantsResult = try context.fetch(request)
  if let variants = variantsResult as? [DBVariant] {
    finalVariants = variants.filter() { $0.variant == true }
  } else {
      finalVariants = []
  }
} catch let error as NSError {
  // Handle error 
  finalVariants = []
}