Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

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.

like image 257
Daij-Djan Avatar asked Jun 04 '14 12:06

Daij-Djan


People also ask

How do you check if an array contains an object in Swift?

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.

How do you check if an array contains a string in Swift?

The contains() method returns: true - if the array contains the specified element. false - if the array doesn't contain the specified element.

Which property that used to check an array has items in Swift?

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.

How do you check if an element belongs to an 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.


1 Answers

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") 
like image 105
jervine10 Avatar answered Oct 13 '22 16:10

jervine10