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

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


//OC
self.lineType = CellExLineTypeTopNone;
self.lineType |= CellExLineTypeBottomNone;
self.lineType = self.lineType & ~CellExLineTypeTopNone; //self.lineTye 只包含CellExLineTypeBottomNone
//Swift
var lineType: CellExLineType = [.topNone, .bottomNone]
lineType.remove(.topNone)

|(按位或):用来添加某个值


//OC
self.lineType = CellExLineTypeTopNone; //self.lineType 包含CellExLineTypeTopNone
self.lineType = self.lineType | CellExLineTypeBottomNone; //self.lineType 包含CellExLineTypeTopNone和CellExLineTypeBottomNone
//Swift
var lineType: CellExLineType = [.bottomNone]
lineType.insert(.topNone)

&(按位与):用来检查是否包含某个值


//OC
if ((self.lineType & CellExLineTypeTopNone) == CellExLineTypeTopNone) {
 NSLog(@"包含CellExLineTypeTopNone");
}
//Swift
var lineType: CellExLineType = [.topNone, .bottomNone]
if lineType.contains(.bottomNone) {
 print("包含bottomNone")
}

^(异或):用来置反某个值(如果包含则剔除,如果不包含则添加)


//OC
self.lineType = CellExLineTypeTopNone | CellExLineTypeBottomNone; //self.lineType 包含CellExLineTypeTopNone和CellExLineTypeBottomNone
self.lineType = self.lineType ^ CellExLineTypeTopNone; //self.lineTye 只包含CellExLineTypeBottomNone
self.lineType = self.lineType ^ CellExLineTypeTopNone; //self.lineType 包含CellExLineTypeTopNone和CellExLineTypeBottomNone
//Swift
var lineType: CellExLineType = [.topNone, .bottomNone]
if lineType.contains(.topNone) {
 lineType.remove(.topNone)
} else {
 lineType.insert(.topNone)
}

在枚举中使用位操作我们可以方便的给一个属性值赋值多个值,比如下面的代码给lineType赋值了CellExLineTypeTopNone和CellExLineTypeBottomNone属性。这样我们就可以在lineType的set方法里面处理CellExLineTypeTopNone和CellExLineTypeBottomNone的情况。


//OC
- (void)setLineType:(CellExLineType)lineType {
 _lineType = lineType;
 if (lineType & CellExLineTypeTopNone) {
  NSLog(@"top none");
 }
 if (lineType & CellExLineTypeBottomNone) {
  NSLog(@"bottom none");
 }
}
//Swift
var lineType: CellExLineType = [.topNone, .bottomNone]
if lineType.contains(.topNone) {
 lineType.remove(.topNone)
}
if lineType.contains(.bottomNone) {
 
}