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)];
}
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.
I tried something like:
func write4ByteField(value: Int32) {
stream.write(&value, maxLength: sizeof(Int32))
}
but I get an error int16 is not convertible to @lvalue inout $T4
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…