Generics swift泛型函数中的位移位
我正在尝试编写一个需要位移位操作的通用函数。我的行为让我无法理解。下面是一个简单的函数来演示这个问题Generics swift泛型函数中的位移位,generics,swift,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 } func testBytes(byte
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
}
func testBytes(bytesIn:[UInt8],inout-dataOut:T){
let outputSize=sizeof(T)
变量温度:T=0
数据输出=0
temp=bytesIn[0]作为T
temp=temp我有一个更详细的例子,但基本上有三个步骤:
从UInt8
使用位移位运算符和构造函数创建新协议:
protocol BitshiftOperationsType {
func <<(lhs: Self, rhs: Self) -> Self
func >>(lhs: Self, rhs: Self) -> Self
init(_ val: UInt8)
}
添加通用约束,使T
符合您的新协议:
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
}
func testBytes(bytesIn:[UInt8],inout-dataOut:T){
let outputSize=sizeof(T)
变量温度:T=0
数据输出=0
温度=T(字节数[0])
temp=temp我准备了一个类似的答案,但是你更快了:-)。我解决第二个问题的方法是将init(val:UInt8)
添加到协议中。所有(有符号和无符号)整数类型都有这样的构造函数,因此你可以使用temp=T(bytesIn[0])进行转换
,并且只需要一个实现。修复得很好!用这个更改更新了答案。非常感谢。我可能会很快提交一个关于底层问题的新问题,因为泛型可能不是我想要的优雅答案。
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
}