0

I need to search whether GENERIC array contains specific element or not in swift.

    var arrProducts = [AnyObject]()

    arrProducts.append(Article())
    arrProducts.append(Flower())
    arrProducts.append(Chocolate())

Here products can be any custom object which I am adding in this array.

Now I want to check if arrProducts contain any of 3 custom class objects

Dhaval H. Nena
  • 3,992
  • 1
  • 37
  • 50

2 Answers2

0

This will check "if arrProducts contain any of 3 custom class objects".

let isContainingAnyOf3CustomClassObject =
    arrProducts.contains {$0 is Article || $0 is Flower || $0 is Chocolate}
//->true

If you need to retrieve all elements of any 3 types, you can use filter.

let elementsOfAny3Types = arrProducts.filter {$0 is Article || $0 is Flower || $0 is Chocolate}

If you want the first element, you can use first.

let firstElementOfAny3Types = arrProducts.filter {$0 is Article || $0 is Flower || $0 is Chocolate}.first

But this may be more efficient:

if let firstMatchingIndex = arrProducts.indexOf({$0 is Article || $0 is Flower || $0 is Chocolate}) {
    let firstMatchingElement = arrProducts[firstMatchingIndex]
    print(firstMatchingElement)
}

If any above are not what you mean, you need to modify your question and describe what you really want to achieve more precisely.

OOPer
  • 47,149
  • 6
  • 107
  • 142
  • Need to search specific element from array which could be of any 3 types! – Dhaval H. Nena Jul 07 '16 at 12:37
  • Checking contains or not and searching the exact element are different things and you'd better clarify such sort of things in your question. I'll update my answer later. – OOPer Jul 07 '16 at 12:43
0

One more method to search for objects of a specific class is flatMap. The benefit of this apporach is that you get an array with the right type.

You have this

class Article { }
class Flower { }
class Chocolate { }

let products : [AnyObject] = [Article(), Flower(), Chocolate()]

Let's extract the flowers

let flowers = products.flatMap { $0 as? Flower }

The flowers array has the following type [Flower] and contains only the right objects.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148