获取 Swift 中 AnyObject 的类型
Get the type of AnyObject in Swift
我有自定义 SkSpriteNode
子class。这个 class 的名字是 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
条件不成立。我正在寻找类似的东西。我需要知道这个 anyObject 的真实类型。我怎么知道的?
谢谢
试试这个。
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")
}
}
我有自定义 SkSpriteNode
子class。这个 class 的名字是 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
条件不成立。我正在寻找类似的东西。我需要知道这个 anyObject 的真实类型。我怎么知道的?
谢谢
试试这个。
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")
}
}