Chad
Chad

Reputation: 275

Test if a list contains element of specific type in Swift

I'm currently trying to write some code that checks to see a list contains an element of a given type T, and am running into trouble. Essentially, this list contains a multitude of elements of different types - however, each of those types are subclassed from one parent type. I've tried

class Entity { }
class Goal : Entity { }
class Player : Entity { }

var entities = [Entity]()
entities.append(Player())

func listContainsClass<T: Entity>(var list: [Entity]) -> Bool {
    for entity in entities {
        if entity is T {
            return true
        }
    }

    return false
}

let contains = listContainsClass<Goal>(entities)

In this case, I get a compiler error stating "cannot explicitly specialize a generic function". If I try to run the function without specifying a generic argument (by only typing listContainsClass(entities)) the compiler exits with a seg-fault 11 code and xCode crashes, which is a separate issue.

I've also tried passing the class type as a parameter instead:

func listContainsClass(var list: [Entity], var type: Entity.Type) -> Bool {
    for entity in entities {
        if entity === type {
            return true
        }
    }

    return false
}

let contains = listContainsClass(entities, Player.self)

But am unsure how to make it work, as it always returns false. Perhaps this is just an old way of thinking, since I am coming from an obj-c background.

Any help on the proper way to do this would be much appreciated!

Upvotes: 1

Views: 492

Answers (2)

David Berry
David Berry

Reputation: 41226

The simplest way to check is to just use the built-in contains function:

contains(entities, { $0 is Player } )

One difference between this and the function you're building is that this will accept further subclasses, where as your function (using ===) won't.

Upvotes: 2

matt
matt

Reputation: 535139

You were so close! Use your second (nongeneric) implementation, and:

if entity.dynamicType === type {

Upvotes: 2

Related Questions