Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a class called Option. This is a Realm object so it's a subclass of Realm's own base class Object.

In a view controller I have an array property that holds a bunch of Option objects.

private var options = [Option]()

In a method down the view controller, I need to check if a certain Option object is contained within the aforementioned options array.

Previously (Swift 1.2), I have the checking logic like this.

func itemSelected(selection: Object) {
    let option = selection as! Option

    if !contains(options, option) {
        // act accordingly
    }
}

Now I'm converting the project to Swift 2 (I have updated the Realm's version to Swift 2 version as well). I updated the code to this.

func itemSelected(selection: Object) {
    let option = selection as! Option

    if !options.contains(option) {
        // act accordingly
    }
}

But now I'm getting the following compile error!

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

I can't figure out why. Any ideas?

like image 867
Isuru Avatar asked Dec 25 '22 12:12

Isuru


1 Answers

This is because the contains function now expects a closure rather than an element on all non-equatable types. All you need to do is change it to the following

if !(options.contains{$0==option}) {
    // act accordingly
}

What this does is it passes a closure in to the function, which returns true only if that closure satisfies any of its elements. $0 stands for the current element in the array that the contains function is testing against, and it returns true if that element is equal to the one that you are looking for.

like image 116
kabiroberai Avatar answered Dec 29 '22 10:12

kabiroberai