Partho Biswas
Partho Biswas

Reputation: 2330

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

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 ?

Upvotes: 0

Views: 4174

Answers (1)

keithbhunter
keithbhunter

Reputation: 12324

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

Upvotes: 4

Related Questions