【问题标题】:Cannot convert value of type '[String : Any]' to expected argument type '([String : Any]) throws -> Bool'无法将“[String : Any]”类型的值转换为预期的参数类型“([String : Any]) throws -> Bool”
【发布时间】:2020-02-04 15:48:40
【问题描述】:

我有 2 个字典数组,我想检查字典的第二个数组是否存在于第一个字典数组中。

let dicA = [[String:Any]]()
let dicB = [[String:Any]]()

if dicA.contains(where: dicB[0]) {
   print("Contains")
}
else {
   print("Not Contains")
}

// 它给了我这样的语法错误:-

  • 无法将 '[String : Any]' 类型的值转换为预期的参数类型 '([String : Any]) throws -> Bool'

【问题讨论】:

  • if dicA.contains(where: dicB[0])) { 你这里有一个双右括号,那就是错误。
  • 这个问题应该是由一个简单的错字引起的。
  • 不是错字
  • 错字是一个问题,但不是唯一的问题。
  • 你们是对的,但我想检查字典的第二个数组中的任何元素( [String:Any] )是否在字典的第一个数组中?

标签: arrays swift dictionary


【解决方案1】:

在编码时花点时间。您的if 语句中不必要的) 是原因之一。

let dicA = [[String:Any]]()
let dicB = [[String:Any]]()

let element = dicB[0]

if dicA.contains(where: { (element) -> Bool in
    print("Contains")
    return true
}) {
}
else {
   print("Not Contains")
}

【讨论】:

  • 你们是对的,但我想检查字典的第二个数组中的任何元素( [String:Any] )是否在字典的第一个数组中?
  • 它不应该仍然编译。您不能将这样的变量设置为element。它代表接收器中的单个元素。
  • 请问我的问题有什么解决方案吗?
【解决方案2】:

Array的contains方法声明是这样的:

func contains(where predicate: (Element) throws -> Bool) rethrows -> Bool

这意味着您的 where 谓词不能是单个参数。它应该是这样的闭包:

if dicA.contains(where: { (element) -> Bool in

    return false

}) {

} else {

}

替换闭包中的逻辑以返回您需要的元素。

【讨论】:

  • 你们是对的,但我想检查字典的第二个数组中的任何元素( [String:Any] )是否在字典的第一个数组中?
  • @AsmaGodil 要编写等式逻辑,我们需要知道字典的字段。有什么独特之处可以比较吗?
猜你喜欢
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
相关资源
最近更新 更多