我正在尝试在Swift中使用 allContactedBodies(),但我一直收到错误'$T5??' does not have a member named 'Generator'
:
class Sense:SKNode { 覆盖init(){ super.init() }
required init(coder: NSCoder) { fatalError("NSCoding not supported") } init(size: CGSize) { // Initialize shape super.init() // Physic Properties self.physicsBody = SKPhysicsBody(rectangleOfSize: size) self.physicsBody?.affectedByGravity = false self.physicsBody?.categoryBitMask = ColliderType.Vision.toRaw() self.physicsBody?.collisionBitMask = 0 self.physicsBody?.contactTestBitMask = ColliderType.Wall.toRaw() self.hidden = true } func contact() -> Bool { for body : AnyObject in self.physicsBody?.allContactedBodies() { // Here is the error return true } return false } }
如何修复它以便我可以使用allContactedBodies()?
答案 0 :(得分:7)
self.physicsBody?.allContactedBodies()
返回一个可选项,因此由于可选链接,这会使整个表达式成为可选项。在self.physicsBody
为零的情况下,您可以使用nil coalescing运算符来使用空数组
for body: AnyObject in self.physicsBody?.allContactedBodies() ?? [] {
return true
}
return false
或使用"如果让"在那里解开物理机构的解开。
if let physicsBody = self.physicsBody {
for body : AnyObject in physicsBody.allContactedBodies() {
return true
}
return false
} else {
return false
}