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

4

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Need to search specific element from array which could be of any 3 types!
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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.