如何通过Objective-C的枚举学习iOS中位操作.md详解

2020-01-21 07:45:02刘景俊


let targetNum = 5 // 101
let targetNum2 = 6 // 110
print(targetNum ^ targetNum2) //print 3
//targetNum: 101
//targetNum2: 110
//result:  011 (十进制 3)

移位

>>(右移):它会对目标数字按位右移x位


let targetNum = 5 // 101
print(targetNum >> 2) //print 1
//targetNum: 101
//右移2位
//result:  1 (十进制 1)

<<(左移):它会对目标数字按位左移x位(右边补0)


let targetNum = 5 // 101
print(targetNum << 2) //print 20
//targetNum: 101
//左移2位
//result:  10100 (十进制 20)

枚举中的位操作

通过上文我们了解了位操作的具体计算方式,接下来看一下在枚举中的具体应用。

枚举中的应用

定义枚举

OC


typedef NS_OPTIONS(NSInteger, CellExLineType) {
 CellExLineTypeTopLong  = 0, 
 CellExLineTypeTopNone  = 1 << 0, //十进制 1
 CellExLineTypeBottomLong = 1 << 1, //十进制 2
 CellExLineTypeBottomNone = 1 << 2, //十进制 4
};

Swift


struct CellExLineType: OptionSet {
 let rawValue: Int
 
 static let topLong = CellExLineType(rawValue: 0)
 static let topNone = CellExLineType(rawValue: 1 << 0)
 static let bottomLong = CellExLineType(rawValue: 1 << 1)
 static let bottomNone = CellExLineType(rawValue: 1 << 2)
}

位操作在枚举中的作用

~(取反):用来剔除某个值