在Swift

时间:2015-05-12 10:38:21

标签: swift skspritenode

我有自定义SkSpriteNode子类。此类的名称为Unit1

GameScene

var allUnit1:[Unit1]?
var enemy1 = Unit1(imageNamed: "1")
enemy1.position = CGPointMake(CGFloat(StartPointX), CGFloat(self.frame.height))

// I add this custom node to array. Its not relative with my 
// question but I want to describe all of them.

if(allUnit1 == nil) {
    allUnit1 = [enemy1]
}
else {
    allUnit1?.append(enemy1)
}

self.addChild(enemy1)
self.getDamage2Unit(self.allUnit1!.first!) 

// My function in gamescene. The problem starts with here. the parameter is AnyObject 
// as you see in below

getDamage2Unit函数是(它也在GameScene中);

func getDamage2Unit(val:AnyObject){
     if(val.type == "Unit1")
        println("this AnyObject is Unit1 objects")
    }
}

if条件不起作用。我正在寻找类似的东西。我需要知道任何对象的真实类型。我怎么知道?

谢谢

1 个答案:

答案 0 :(得分:1)

试试这个。

func getDamage2Unit(val:AnyObject){
     if let myType = val as? Unit1 {
        println("this AnyObject is Unit1 objects")
    }
}

现在,如果您知道val将始终为Unit1类型,那么请将AnyObject更改为Unit1

func getDamage2Unit(val:AnyObject) {
let myType = val as Unit1?
         if myType != nil {
            println("this AnyObject is Unit1 objects")
        }
    }