【问题标题】:Swift: Cannot convert value of type 'String' to expected argument type '@noescape (AnyObject) throws -> Bool'Swift:无法将“String”类型的值转换为预期的参数类型“@noescape (AnyObject) throws -> Bool”
【发布时间】:2016-04-25 17:45:15
【问题描述】:

我知道这是一个简单的问题,但我在寻找解决方案时遇到了问题。

在 Swift 2.2 中,我收到此错误。

无法将“字符串”类型的值转换为预期的参数类型 '@noescape (AnyObject) 抛出 -> Bool'

这里是代码。

var tableDataSectionsDict: CHOrderedDictionary?
if !tableDataSectionsDict!.allKeys.contains("Yesterday") {
   tableDataSectionsDict!.insertObject(YesterdayArray, forKey: "Yesterday", atIndex: count)
}

我在这里缺少什么?有人可以给它遮光吗?

【问题讨论】:

  • 查看contains函数的定义。它期望闭包,而不是字符串。
  • @AlexanderDoloz 有 2 个contains 函数;一个期望一个闭包,一个期望一个元素。看起来这是一个AnyObjects 的字典,所以当传递一个字符串时类型推断可能会混淆。
  • OP 使用CHOrderedDictionary。也许它只有 1 个contains 函数:)

标签: ios arrays swift swift2 ios9


【解决方案1】:

我假设CHOrderedDictionary 是this CHOrderedDictionary。如果是这种情况,那么它是您已桥接到 Swift 的 Objective-C 类型(如果我错了,请纠正我)。

有两个contains 函数可用:

extension SequenceType where Generator.Element : Equatable {
    /// Returns `true` iff `element` is in `self`.
    @warn_unused_result
    public func contains(element: Self.Generator.Element) -> Bool
}

extension SequenceType {
    /// Returns `true` iff an element in `self` satisfies `predicate`.
    @warn_unused_result
    public func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool
}

CHOrderedDictionary 的键和值从 Objective-C 中的 id 转换为 Swift 中的 AnyObject。 AnyObject不符合Equatable,所以不能使用第一个contains函数。如果你真的想的话,你可以写一个 CHOrderedDictionary 的包装器来允许一些 Equatable 元素类型。

这里最快的解决方案是使用更通用的contains 版本(第二个contains)。在代码中,它看起来像这样:

// contains will iterate over the entire allKeys array. $0 is the key at each iteration.
let containsKey = tableDataSectionsDict!.allKeys.contains { return $0 as? String == "Yesterday" }
if !containsKey {
    //...
}

【讨论】:

  • 是的,你是对的。我正在为这个 CHOrderedDictionary Objective-C 类使用一个桥接头。并感谢代码示例。效果很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多