I am trying to convert this piece of code to Swift:
NSData *testData = [@"Whatever" dataUsingEncoding:NSUTF8StringEncoding];
void (^whatever)(NSOutputStream *) = ^(NSOutputStream *stream) {
[stream open];
NSRange myRange = {0};
while (myRange.location < testData.length) {
myRange.location += myRange.length;
myRange.length = 4096;
if (myRange.location + myRange.length > testData.length) {
myRange.length = testData.length - myRange.location;
}
[stream write:&(testData.bytes[myRange.location])
maxLength:myRange.length];
}
[stream close];
};
Unfortunately, i am really stuck on &(testData.bytes[myRange.location])
.
The swift converters i found online don't process that part at all, and Swift compiler complains that:
Value of type 'UnsafeRawPointer' has no subscripts
The examples with .withUnsafeBytes
don't show how to get the bytes pointer at a specific location.
Here's the swift:
let testData = "Whatever".data(using: .utf8)!
let whatever: ((OutputStream) -> Void)? = { stream in
stream.open()
var myRange = NSRange()
while myRange.location < testData.count {
myRange.location += myRange.length
myRange.length = 4096
if myRange.location + myRange.length > testData.count {
myRange.length = testData.count - myRange.location
}
// the next line doesn't work
stream.write(testData.bytes[myRange.location], maxLength: myRange.length)
}
stream.close()
}