generics - 快速通用函数中的位移位

标签 generics swift

我正在尝试编写一个需要移位操作的通用函数。我遇到了我不理解的行为。这是一个演示问题的简单函数。

func testBytes<T: IntegerType>(bytesIn: [UInt8], inout dataOut: T){

let outputSize = sizeof(T)
var temp: T = 0
dataOut = 0
temp = bytesIn[0] as T
temp = temp << 1

}

如果我这样做,最后一行会在 xcode 中给出一个错误“T is not convertible to Int”。

我可以将最后一行更改为 temp = temp << (1 as T)

然后此行的错误更改为“T 不可转换为 UInt8”

在这种情况下,这些错误消息中的任何一条对我来说都没有意义。我可以做些什么来启用泛型类型的位移位吗?

最佳答案

我有一个 blog post on this topic更详细,但基本上分为三个步骤:

  1. 使用位移运算符和来自 UInt8 的构造函数创建一个新协议(protocol):

    protocol BitshiftOperationsType {
        func <<(lhs: Self, rhs: Self) -> Self
        func >>(lhs: Self, rhs: Self) -> Self
        init(_ val: UInt8)
    }
    
  2. 声明符合每个整数类型的扩展 - 很容易,因为它们已经在 BitshiftOperationsType 中实现了所有内容:

    extension Int    : BitshiftOperationsType {}
    extension Int8   : BitshiftOperationsType {}
    extension Int16  : BitshiftOperationsType {}
    extension Int32  : BitshiftOperationsType {}
    extension Int64  : BitshiftOperationsType {}
    extension UInt   : BitshiftOperationsType {}
    extension UInt8  : BitshiftOperationsType {}
    extension UInt16 : BitshiftOperationsType {}
    extension UInt32 : BitshiftOperationsType {}
    extension UInt64 : BitshiftOperationsType {}
    
  3. 添加通用约束,使 T 符合您的新协议(protocol):

    func testBytes<T: IntegerType where T: BitshiftOperationsType>(bytesIn: [UInt8], inout dataOut: T){
        let outputSize = sizeof(T)
        var temp: T = 0
        dataOut = 0
        temp = T(bytesIn[0])
        temp = temp << 1
    }
    

感谢 Martin R. 修复了我之前在这里遇到的问题!

关于generics - 快速通用函数中的位移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26716673/

相关文章:

generics - 为什么在 "out"位置考虑函数参数中的逆变类型参数?

java - jackson JSON + Java 泛型

scala - 光滑的表不带类型参数

ios - 如何在 Swift 中找到正确的路径

swift - Swift 中索引为 3 的 UITableViewEditingStyle

java - 定义功能性 Java API 时,通用通配符的正确用法是什么?

c# - 类型参数中具有层次结构的受限泛型

ios - 将 float 限制为小数点后两位,并为 Swift 中的数字提供逗号分隔格式

objective-c - Swift 中的 EKEventStore enumerateEventsMatchingPredicate

SKProduct 的 swift 应用内购买问题