Bit shift OptionSet 是 7 的倍数? Swift 3
Bit shift OptionSet is multiples of 7? Swift 3
位移选项集...
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
match
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
match
O:2 T:7
match
O:4 T:7
match
1 + 2 + 4 = 7 = 二进制 111
位移选项集...
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
match
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
match
O:2 T:7
match
O:4 T:7
match
1 + 2 + 4 = 7 = 二进制 111