Fayyouz Fayyouz - 6 months ago 30
Swift Question

checking if scene contains nodes of specific type

In my SKScene, I want to check if there are any nodes that are of a specific type. And because I need something like this multiple times, I was trying to create the following function, that takes a type as a function, but it doesn't compile, any help please?

extension SKNode {
func containsObject(ofType type: Any) -> Bool {
return children.contains(where {$0 is type}) ? true : false

The error:

Use of undeclared type 'type'

Answer Source

You need to make your function a generic function and check the generic type parameter instead of the input argument.

extension SKNode{
    func containsObject<T>(ofType: T.Type) -> Bool {
        return children.contains(where: {$0 is T})

This is, how you call it:

let node  = SKNode()

class MyNode: SKNode {
    var title = ""

let myNode = MyNode()

node.containsObject(ofType: MyNode.self) //returns true

let otherNode = SKNode()
otherNode.containsObject(ofType: MyNode.self) //returns false
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download