Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
swift中的位运算和算术运算_Swift_Bitwise Operators_Swift3 - Fatal编程技术网

swift中的位运算和算术运算

swift中的位运算和算术运算,swift,bitwise-operators,swift3,Swift,Bitwise Operators,Swift3,老实说,从obj-c移植到SWIFT3非常困难。最简单但最快的问题 public func readByte() -> UInt8 { // ... } public func readShortInteger() -> Int16 { return (self.readByte() << 8) + self.readByte(); } 从编译器获取错误消息:二进制运算符+不能应用于两个UInt8操作数 怎么了 附言:真可惜 readByte返回UIn

老实说,从obj-c移植到SWIFT3非常困难。最简单但最快的问题

public func readByte() -> UInt8
{
    // ...
}

public func readShortInteger() -> Int16
{
    return (self.readByte() << 8) + self.readByte();
}
从编译器获取错误消息:二进制运算符+不能应用于两个UInt8操作数

怎么了

附言:真可惜

readByte返回UInt8,因此:

不能将UInt8向左移位8位,将丢失其所有位。 表达式的类型为UInt8,它不能适合它正在计算的Int16值。 表达式的类型是UInt8,它不是带注释的返回类型Int16。 d

虽然Swift对操作数有严格的左右求值顺序,但我对代码进行了重构,以明确哪个字节先读取,哪个字节后读取

此外,OR运算符更具有自文档性和语义性。

readByte返回UInt8,因此:

不能将UInt8向左移位8位,将丢失其所有位。 表达式的类型为UInt8,它不能适合它正在计算的Int16值。 表达式的类型是UInt8,它不是带注释的返回类型Int16。 d

虽然Swift对操作数有严格的左右求值顺序,但我对代码进行了重构,以明确哪个字节先读取,哪个字节后读取


此外,OR操作员更具有自我记录和语义。

苹果公司在这方面有一些很棒的Swift文档,如下所示:


苹果在这方面有一些很棒的Swift文档,如下所示:


这里不需要var,因为您没有进行任何突变:而且,简单地让类型推断通过let highByte=self.readByte完成其工作,而不是单独进行类型声明,这将更为惯用。@TimVermeulen哦!谢谢你的改进!应该是int8,只是打印错误。实际的codecoaamf:-int16_-tdecodeShort{[self-ensureLength:2];int8_-tch1=m_字节[m_-position++];int8_-tch2=m_字节[m_-position++];return ch1此处不需要var,因为您没有进行任何突变。:另外,更惯用的做法是简单地让类型推断通过let highByte=self.readByte完成其工作,而不是单独进行类型声明。@TimVermeulen哦!感谢您的改进!应该在int8上签名,只是打印错误。实际的codecoaamf:-int16_-tdecodeShort{[self-ensureLength:2];int8_-ch1=m_字节[m_-position++];int8_-ch2=m_字节[m_-position++];返回ch1
func readShortInteger() -> Int16
{
    let highByte = self.readByte()
    let lowByte = self.readByte()

    return Int16(highByte) << 8 | Int16(lowByte)
}
let shiftBits: UInt8 = 4   // 00000100 in binary
shiftBits << 1             // 00001000
shiftBits << 2             // 00010000
shiftBits << 5             // 10000000
shiftBits << 6             // 00000000
shiftBits >> 2             // 00000001