gpt4 book ai didi

swift - 为什么我们不能将连续的 rawValue 设置为选项集?

转载 作者:搜寻专家 更新时间:2023-10-31 22:25:33 24 4
gpt4 key购买 nike

今天我尝试在 Playground 中使用 OptionSet 进行一些操作,我注意到了这种模式

 struct Activities: OptionSet {
let rawValue: Int
static let eating = Activities(rawValue: 1)
static let programming = Activities(rawValue: 2)
static let breathing = Activities(rawValue: 3)
static let saveGotham = Activities(rawValue: 4)
}

let act: Activities = [.eating, .programming, .saveGotham]

act.contains(.breathing). //true /* this is unexpected */
act.contains(.saveGotham) //true

尽管该数组不包含值“.breathing”,但它仍会返回 true。我用不同的 rawValue 修改了相同的结构

 struct Activities: OptionSet {
let rawValue: Int
static let eating = Activities(rawValue: 1)
static let programming = Activities(rawValue: 8)
static let breathing = Activities(rawValue: 16)
static let saveGotham = Activities(rawValue: 32)
}

let act: Activities = [.eating, .programming, .saveGotham]

act.contains(.breathing). //false
act.contains(.saveGotham) //true

并得到了想要的输出。如果有人能阐明问题并解释“OptionSet”的实际工作原理,那就太棒了。

谢谢。

最佳答案

OptionSet protocol是为了

... represent bitset types, where individual bits represent members of a set.

在你的情况下,

let act: Activities = [.eating, .programming, .saveGotham]
print(act.rawValue) // 7

存储为包含原始值的按位或的整数(1 | 2 | 4 = 7)

  act.contains(.breathing). //true /* this is unexpected */

测试 BITWISE AND 7 & 3 是否为非零(是这种情况)。

因此你不应该使用连续的原始值,而应该使用两个,即每个互斥值由一个表示比特位:

struct Activities: OptionSet {
let rawValue: Int
static let eating = Activities(rawValue: 1)
static let programming = Activities(rawValue: 2)
static let breathing = Activities(rawValue: 4)
static let saveGotham = Activities(rawValue: 8)
}

或等同于:

struct Activities: OptionSet {
let rawValue: Int
static let eating = Activities(rawValue: 1 << 0)
static let programming = Activities(rawValue: 1 << 1)
static let breathing = Activities(rawValue: 1 << 2)
static let saveGotham = Activities(rawValue: 1 << 3)
}

现在一切正常:

let act: Activities = [.eating, .programming, .saveGotham]
print(act.rawValue) // 11
print(act.contains(.breathing)) // false
print(act.contains(.saveGotham)) // true

关于swift - 为什么我们不能将连续的 rawValue 设置为选项集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48582350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com