如何在Swift中将Int32写入NSOutputStream
我正在尝试在Swift中将Int32写入NSOutputStream,但遇到了困难.在ObjC中,我会做这样的事情:
I'm trying to write an Int32 to an NSOutputStream in Swift and I'm having difficulties. In ObjC, I would have done something like this:
-(void)write4ByteField:(int32_t)value {
[stream write:((value >> 24) & 0xff)];
[stream write:((value >> 16) & 0xff)];
[stream write:((value >> 8) & 0xff)];
[stream write:(value & 0xff)];
}
但是,在Swift中,我真的不喜欢我做所有的低级位移位操作,而我放弃了在所有位置上强制转换值.
However, in Swift, it really doesn't like me doing all of that low-level bit-shifting and I gave up on casting the values all over the place.
我尝试过类似的事情:
func write4ByteField(value: Int32) {
stream.write(&value, maxLength: sizeof(Int32))
}
但出现错误int16 is not convertible to @lvalue inout $T4
类似地,如果我尝试转到NSData,则会收到相同的错误:
Similarly, if I try to go to NSData I get the same error:
func write4ByteField(value: Int32) {
let data = NSData(bytes: &value, length: sizeof(Int32)
stream.write(data.bytes, maxLength: sizeof(Int32))
}
有什么建议吗?我猜我只是在以错误的方式来做.
Any suggestions? I'm guessing I am just going about this the wrong way.
您的最后一种方法几乎是正确的. value
必须是一个变量参数
这样您就可以将其用作输入输出表达式" &value
,并且data.bytes
需要强制转换:
Your last approach is almost correct. value
needs to be a variable parameter
so that you can use it as "in-out expression" &value
, and data.bytes
needs a cast:
func write4ByteField(var value: Int32) {
let data = NSData(bytes: &value, length: sizeof(Int32))
stream.write(UnsafePointer(data.bytes), maxLength: sizeof(Int32))
}
也可以在没有NSData
的情况下完成,包括转换为big-endian
字节顺序:
It can also be done without NSData
, including the conversion to big-endian
byte order:
func write4ByteField(value: Int32) {
var valueBE = value.bigEndian
withUnsafePointer(&valueBE) {
self.stream.write(UnsafePointer($0), maxLength: sizeofValue(valueBE))
}
}