【问题标题】:Contextual type cannot be used with dictionary literal上下文类型不能与字典文字一起使用
【发布时间】:2018-04-06 23:32:02
【问题描述】:

我有一个字典数组,只想检查数组是否包含某个值。但是,我收到此错误消息:

上下文类型 '([Double : Double]) throws -> Bool' 不能与字典文字一起使用

代码:

if stored.contains(where: ([YAngle : ZAngle])) { // Error on this line
    print("This data is already stored")
}

我做错了什么?

【问题讨论】:

    标签: arrays swift swift4


    【解决方案1】:

    您对 contains(where:) 的使用不正确。这是一个不会导致编译器错误的函数用法示例:

    if stored.contains(where: { (key, value) -> Bool in
        return true
    }) {
        // no op
    }
    

    您可能想要检查字典是否包含键值对只是:

    if stored[YAngle] == ZAngle {
        print("This data is already stored")
    }
    

    【讨论】:

      【解决方案2】:

      contains(where:) 将函数作为参数。它适用于数组的元素类型不符合Equatable 协议或者您需要在检查过程中执行其他逻辑时使用。有两种方法可以做到这一点:

      [Double:Double] 符合Equatable,因此,由于您只是进行简单比较,因此您可以改用contains(_:)(即只需删除where:):

      if stored.contains([YAngle : ZAngle]) {
          print("This data is already stored")
      }
      

      如果您要进行更复杂的检查,或者您的类型不符合 Equatable,您可以传入一个函数:

      if stored.contains(where: { dict in
          // Here you would do your logic and return a boolean based on the result.
          // If you really wanted to do it this way with your current data
          // you could do this:
          return dict == [YAngle:ZAngle]
      }) {
          print("This data is already stored")
      }
      

      【讨论】:

      • 旁注:标准的 Swift 约定总是以小写字母开头变量。我花了一段时间才弄清楚您的代码中发生了什么,因为我认为 YAngleZAngle 是类型而不是变量。请改用yAnglezAngle
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多