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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With