检查场景是否包含特定类型的节点

时间:2017-08-23 10:23:57

标签: ios swift sprite-kit

在我的SKScene中,我想检查是否有任何特定类型的节点。因为我需要多次这样的东西,我试图创建以下函数,它将一个类型作为一个函数,但它不编译,请帮忙吗?

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

错误:

  

使用未声明的类型'type'

2 个答案:

答案 0 :(得分:4)

您需要使您的函数成为泛型函数并检查泛型类型参数而不是输入参数。

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

这就是你怎么称呼它:

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

答案 1 :(得分:1)

为什么不使用这样的数组函数?

let a: [AnyObject] = ["a" as AnyObject]

if a.contains(where: {$0 is String}) {
    print("a")
}

SKNode

的示例
class MyNode: SKNode {

}

let a = SKNode()

a.children.contains(where: ({$0 is MyNode}))

a.addChild(MyNode())

a.children.contains(where: ({$0 is MyNode}))

包裹

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

class MyNode: SKNode {

}

let a = SKNode()

a.containsObject(ofType: MyNode.self)

a.addChild(MyNode())

a.containsObject(ofType: MyNode.self)