我正在尝试编写一个需要移位操作的通用函数。我的行为我不理解。这是一个演示该问题的简单函数。
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 无法转换为 Int”。
我可以将最后一行更改为temp = temp << (1 as T)
然后该行的错误更改为“T 无法转换为 UInt8”
在这种情况下,这些错误消息对我来说都没有意义。我可以做些什么来启用通用类型的位移位吗?
我有一个关于此主题的博客文章 http://natecook.com/blog/2014/08/generic-functions-for-incompatible-types/这更详细,但本质上分为三个步骤:
-
使用位移运算符和构造函数创建一个新协议UInt8
:
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
符合您的新协议:
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. 修复了我之前在这里遇到的问题!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)