swift - Bit shift OptionSet 是 7 的倍数? swift 3

标签 swift bitwise-operators bit-shift

位移选项集...

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

两个问题....

  1. 为什么位移位是 7 的倍数而不是 1 的倍数?
  2. 为什么 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/

相关文章:

ios - 快速按下按钮时填充按钮图标

ios - 如何在文件管理器中保存多个图像

swift - Sinch VoIP ManagedPush 通知不起作用(Swift)

vbscript - 为什么 VBScript 的按位 And 在一种情况下失败?

c - 从txt文件中读取字符,编码并写入二进制文件

c - sarq 和 shrq 的区别

ios - 如何将 Realm 对象类添加到 RLMArray

php - PHP 中的 Xor 加密

c# - C# 中左移位的奇怪行为

java - 需要帮助来理解此代码以找到给定数字中 1 的位置