0
votes

I know this is a simple question, yet i am having problem finding the solutions.

In Swift 2.2, I am getting this error.

Cannot convert value of type 'String' to expected argument type '@noescape (AnyObject) throws -> Bool'

Here is the code.

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

enter image description here

What i am missing here ? Can anybody shade some light on it ?

1
Look at definition of contains function. It expects closure, not a String. - Alexander Doloz
@AlexanderDoloz There are 2 contains functions; one expects a closure, and one expects an element. It looks like this is a dictionary of AnyObjects, so the type inference might be getting confused when passed a string. - NobodyNada
OP uses CHOrderedDictionary. Maybe it has only 1 contains function :) - Alexander Doloz

1 Answers

4
votes

I'm assuming that CHOrderedDictionary is this CHOrderedDictionary. If that's the case, it is an Objective-C type that you have bridged to Swift (please correct me if I'm wrong).

There are two contains functions available:

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's keys and values are converted from id in Objective-C to AnyObject in Swift. AnyObject does not conform to Equatable, so you cannot use the first contains function. You could proabably write a wrapper around CHOrderedDictionary to allow some Equatable element types if you really wanted to.

The fastest solution here will be to use the more generic version of contains (the second contains). In code, it would look something like this:

// 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 {
    //...
}