OC中的NSOptions通过位运算可以实现多选枚举,swift版本如下:
struct StringJoinType: OptionSet {
let rawValue: Int
static let joinName = StringJoinType(rawValue: 1 << 0)
static let joinAge = StringJoinType(rawValue: 1 << 1)
static let joinAddress = StringJoinType(rawValue: 1 << 2)
static let joinJob = StringJoinType(rawValue: 1 << 3)
static let joinBase: StringJoinType = [.joinName, .joinAge]
static let joinAll: StringJoinType = [.joinBase, .joinAddress, .joinJob]
}
创建struct
实现OptionSet
协议,并通过位运算定义枚举值。枚举值的使用例子:
通过枚举值创建一个字符串
func optionsTest() -> String {
let type: StringJoinType = .joinBase
var result = ""
if (type.contains(.joinName)) {
result.append("Albert")
}
if (type.contains(.joinAge)) {
result.append("12")
}
if (type.contains(.joinAddress)) {
result.append("github")
}
if (type.contains(.joinJob)) {
result.append("iOS")
}
return result //输出结果:Albert12
}