【发布时间】:2023-04-02 23:12:01
【问题描述】:
我正在尝试编写一个辅助函数,它将位索引数组转换为符合 OptionSet 的类。
func getOptionSet<T: OptionSet>(bitIndexes: [Int64]) -> T {
var result: Int64 = 0
for index in bitIndexes {
result |= 1 << index
}
return T(rawValue: result) // error
}
编译失败:
Cannot invoke initializer for type 'T' with an argument list of type '(rawValue: Int64)'
我也尝试过使用 RawValue:
func getOptionSet<T: OptionSet>(bitIndexes: [T.RawValue]) {
var result = T.RawValue() // error
这也不行:
Cannot invoke value of type 'T.RawValue.Type' with argument list '()'
这可以吗?我需要在 T 上添加额外的约束吗?
我知道可以重写此函数以使用具体类型,但如果可能,我希望保持其通用性。
【问题讨论】:
标签: swift generics bit-fields swift3 bitvector