How to define category bit mask enumeration for SpriteKit in Swift? How to define category bit mask enumeration for SpriteKit in Swift? swift swift

How to define category bit mask enumeration for SpriteKit in Swift?


What you could do is use the binary literals: 0b1, 0b10, 0b100, etc.

However, in Swift you cannot bitwise-OR enums, so there is really no point in using bitmasks in enums. Check out this question for a replacement for NS_OPTION.


If you look at this swift tutorial, you can avoid the whole toRaw() or rawValue conversion by using:

struct PhysicsCategory {  static let None      : UInt32 = 0  static let All       : UInt32 = UInt32.max  static let Monster   : UInt32 = 0b1       // 1  static let Projectile: UInt32 = 0b10      // 2}monster.physicsBody?.categoryBitMask = PhysicsCategory.Monster monster.physicsBody?.contactTestBitMask = PhysicsCategory.Projectile monster.physicsBody?.collisionBitMask = PhysicsCategory.None 


Take a look at the AdvertureBuilding SpriteKit game. They rebuilt it in Swift and you can download the source on the iOS8 dev site.

They are using the following method of creating an enum:

enum ColliderType: UInt32 {  case Hero = 1  case GoblinOrBoss = 2  case Projectile = 4  case Wall = 8  case Cave = 16}

And the setup is like this

physicsBody.categoryBitMask = ColliderType.Cave.toRaw()physicsBody.collisionBitMask = ColliderType.Projectile.toRaw() | ColliderType.Hero.toRaw()physicsBody.contactTestBitMask = ColliderType.Projectile.toRaw()

And check like this:

func didBeginContact(contact: SKPhysicsContact) {// Check for Projectile    if contact.bodyA.categoryBitMask & 4 > 0 || contact.bodyB.categoryBitMask & 4 > 0   {          let projectile = (contact.bodyA.categoryBitMask & 4) > 0 ? contact.bodyA.node : contact.bodyB.node    }}