Monday, October 13, 2014

Swift - Dealing with pointers in Swift

When using certain APIs in Objective-C and C, you often have to deal with pointers. For example, you can write data to the NSOutStream object using the write:maxLength: method:

-(void) writeToServer:(const uint8_t *) buf {
    [oStream write:buf maxLength:strlen((char*)buf)];

}

The write:maxLength: method takes in a pointer of type unint8_t, containing the data you want to send across the stream. The equivalent of the above function in Swift is:

func writeToServer(dataToWrite:NSData) { 
    oStream!.write(
        UnsafePointer(dataToWrite.bytes)
        maxLength: dataToWrite.length) 
}

For reading of data, in Objective-C, you would supply an array of uint8_t:

uint8_t buf[1024]; 
unsigned int len = 0; 
len = [(NSInputStream *)stream read:buf maxLength:1024];

In Swift, you can use the following:

let buf = NSMutableData(capacity: 1024) 
var buffer = UnsafeMutablePointer(buf.bytes) 
let len = (aStream as NSInputStream).read(buffer, maxLength: 1024)

No comments: