位移选项集...
struct VerifiedOptions : OptionSet {
let rawValue: Int
static let facebook = VerifiedOptions(rawValue: 1 << 0)
static let email = VerifiedOptions(rawValue: 1 << 1)
static let phoneNumber = VerifiedOptions(rawValue: 1 << 2)
static let count:Int = 3
}
像这样使用...
let options:VerifiedOptions = [.facebook,.email,.phoneNumber]
for i in 0..<VerifiedOptions.count {
let option = VerifiedOptions(rawValue: options.rawValue << i)
print("O:",option.rawValue,"T:",options.rawValue)
if options.contains(option) { print("match") }
}
打印解析为
O:7 T:7
匹配
O:14 T:7
O:28 T:7
两个问题....
- 为什么位移位是 7 的倍数而不是 1 的倍数?
- 为什么
options
没有显示为包含所有 3 个选项?
感谢您的宝贵时间。
最佳答案
不好意思,马上捕获了
let option = VerifiedOptions(rawValue: options.rawValue << i)
应该是
let option = VerifiedOptions(rawValue: 1 << i)
打印出来的是
O:1 T:7
匹配
O:2 T:7
匹配
O: 4 T:7
匹配
1 + 2 + 4 = 7 = 二进制 111
关于swift - Bit shift OptionSet 是 7 的倍数? swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44464132/