How to define category bit mask enumeration for Sp

2020-02-17 05:24发布

To define a category bit mask enum in Objective-C I used to type:

typedef NS_OPTIONS(NSUInteger, CollisionCategory)
{
    CollisionCategoryPlayerSpaceship = 0,
    CollisionCategoryEnemySpaceship = 1 << 0,
    CollisionCategoryChickenSpaceship = 1 << 1,
};

How can I achieve the same using Swift? I experimented with enums but can't get it working. Here is what I tried so far.

error screenshot

9条回答
混吃等死
2楼-- · 2020-02-17 06:02

Swift 3 with enum:

enum PhysicsCategory: UInt32 {
  case none = 1
  case monster = 2
  case projectile = 4
  case wall = 8
}

monster.physicsBody?.categoryBitMask = PhysicsCategory.monster.rawValue 
monster.physicsBody?.contactTestBitMask = PhysicsCategory.projectile.rawValue
monster.physicsBody?.collisionBitMask = PhysicsCategory.none.rawValue 
查看更多
迷人小祖宗
3楼-- · 2020-02-17 06:08

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.

查看更多
混吃等死
4楼-- · 2020-02-17 06:08

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 
查看更多
登录 后发表回答