Fayyouz Fayyouz - 1 month ago 10
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.addChild(myNode)

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

let otherNode = SKNode()
otherNode.addChild(SKNode())    
otherNode.containsObject(ofType: MyNode.self) //returns false