Randy Randy - 4 months ago 8
Swift Question

How to iterate over an array and check element type at the same time in swift?

I'd like to know if it is possible to iterate over an array is swift and check if the current element has a certain type.
A use case would be : I have an array with

NSDictionary
s and
NSArray
s and I ony want to take care of the
NSDictionary
s.

I'd like to do this without the condition inside the loop :

for entity in array
{
if entity is NSDictionary
{
// Do something
}
}


I'm looking for something like :

for (entity in array) as? NSDictionary
{
// Do something
}


Of course I know that what I have just written doesn't work, but I guess you can get the idea of what I'm asking for.

Any idea would be really appreciated !

Answer

Solution 1

You can filter your array

let things = [NSDictionary(), NSArray(), NSDictionary(), NSArray()]

let dicts = things.flatMap { $0 as? NSDictionary }

Now dicts is defined as [NSDictionary] an contains only the 2 dictionaries.

Solution 2

You can also perform a for loop only on the values that are dictionaries

let things = [NSDictionary(), NSArray(), NSDictionary(), NSArray()]

for dict in things.flatMap( { $0 as? NSDictionary }) {

}