位移OptionSet是7的倍数?斯威夫特3

时间:2017-06-09 17:59:51

标签: swift bitwise-operators bit-shift

位移OptionSet ...

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

两个问题......

  1. 为什么位移7的倍数而不是1的倍数?
  2. 为什么options显示为不包含所有3个选项?
  3. 感谢您的时间。

1 个答案:

答案 0 :(得分:1)

抱歉,立即抓住了

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