I'm 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 that's what it looks like.
It's easy to find out whether an array contains a specific value, because Swift has a contains() method that returns true or false depending on whether that item is found. For example: let array = ["Apples", "Peaches", "Plums"] if array.
The contains() method returns: true - if the array contains the specified element. false - if the array doesn't contain the specified element.
Use the isEmpty property to check quickly whether an array has any elements, or use the count property to find the number of elements in the array.
The simplest and fastest way to check if an item is present in an array is by using the Array. indexOf() method. This method searches the array for the given item and returns its index. If no item is found, it returns -1.
Swift 1:
let array = ["1", "2", "3"] let contained = contains(array, "2") println(contained ? "yes" : "no")
Swift 2, 3, 4:
let array = ["1", "2", "3"] let contained = array.contains("2") print(contained ? "yes" : "no")
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