我正在尝试编写一个需要移位操作的通用函数。我遇到了我不理解的行为。这是一个演示问题的简单函数。
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更详细,但基本上分为三个步骤:
使用位移运算符和来自
UInt8
的构造函数创建一个新协议(protocol):protocol BitshiftOperationsType { func <<(lhs: Self, rhs: Self) -> Self func >>(lhs: Self, rhs: Self) -> Self init(_ val: UInt8) }
声明符合每个整数类型的扩展 - 很容易,因为它们已经在
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 {}
添加通用约束,使
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/