Daij-Djan Daij-Djan - 4 months ago 20
Swift Question

Swift arrays and contains, how to determine if a collection contains an object or value?

Im at it again with swift arrays and containsObject provided by NSArray only!

I bridge the swift array to NSArray to do that contains:

extension Array {
func contains(object:AnyObject!) -> Bool {
if(self.isEmpty) {
return false
}
let array: NSArray = self.bridgeToObjectiveC();
return array.containsObject(object)
}
}


it works fine in general but as soon as I put a String! in an array of type String, it crashes. Even though containsObject does take a AnyObject!

var str : String! = "bla"
var c = Array<String>();
c.append(str)
println(c.contains(str))


declaring a String! array also doesn't help

var str : String! = "bla"
var c = Array<String!>();
c.append(str)
println(c.contains(str))


BUT the same without ! works fine

var str : String = "bla"
var c = Array<String>();
c.append(str)
println(c.contains(str))


SO how do I explicitly wrap stuff? I don't really see why I'd have to explicitly wrap it only so it is right unwrapped but thats what it looks like...

Answer

Swift 1:

var array = ["1", "2", "3"]
var contained = contains(array, "2")
println(contained ? "yes" : "no")

Swift 2:

var array = ["1", "2", "3"]
var contained = array.contains("2")
println(contained ? "yes" : "no")