使用 Swift 1.2,我试图专门为 Bool 类型扩展数组类以返回 Int 中的位集值。尝试了很多方法后我无法让它工作:
extension Array {
func toUInt32<T: BooleanType>(Void) -> UInt32 {
let numBits = self.count
assert(numBits < 32)
var result: UInt32 = 0
for (idx, bit) in enumerate(self) {
if bit {
result |= UInt32(1 << (7 - (idx % 8)))
}
}
return result
}
}
我不清楚为什么不能以这种方式测试位变量中 Bool 数组的枚举。我也不确定如何为单一类型扩展数组类(这里使用的是 BooleanType。)我做错了什么?
最佳答案
您目前(Swift 1.2)不能使用对该函数的泛型类型施加进一步约束的方法来扩展现有的泛型类型。因此,在此示例中,您不能编写要求数组包含 bool 值的方法。
相反,您可以编写一个将数组(或任何集合)作为参数的自由函数,然后要求该集合包含 bool 值:
func toUInt32<C: CollectionType where C.Generator.Element: BooleanType>(source: C) -> UInt32 {
let numBits = count(source)
assert(numBits < 32)
var result: UInt32 = 0
for (idx, bit) in enumerate(source) {
if bit {
// guessing you meant |= rather than != ?
result |= UInt32(1 << (7 - (idx % 8)))
}
}
return result
}
关于ios - bool 扩展数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686007/