ios - bool 扩展数组

标签 ios swift

使用 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/

相关文章:

ios - 如何将 UITextField 添加到 CALayer 并使其工作

ios - UITableView 多选的选定复选标记未保持选中状态

ios - 无法在 Xcode 中使用 PFImageView

ios - 尝试将 json 发布到服务器时出错 Code=3840

ios - UISwitch 设置状态

objective-c - 如何在工具栏中自动布局项目

ios - 带协议(protocol)的动态初始化程序

ios - 从 iOS 错误路径上的 Documents 文件夹内的文件夹保存和获取图像

iOS 检测 3G 或 WiFi

ios - tableView 中的自定义分隔符