SWIFT ONLY — Reading from NSInputStream

Solutions Collect From Internet About “SWIFT ONLY — Reading from NSInputStream”

I have figured it out myself.

Look at this simple code:

let data: NSData = "Jonathan Yaniv.".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let stream: NSInputStream = NSInputStream(data: data)

var buffer = [UInt8](count: 8, repeatedValue: 0)


if stream.hasBytesAvailable {
    let result :Int = stream.read(&buffer, maxLength: buffer.count)

//  result = 8 -- because of the size of the buffer.
//  buffer contains the first 8 bytes repreenting the word "Jonathan"

The read method signature:
stream.read(<#buffer: UnsafeMutablePointer#>, maxLength: <#Int#>)

It gets a UnsafeMutablePointer as a first parameter, which means the method expects to get a POINTER to an array of type UInt8 – NOT the array itself

Therefore, we add the & notation before the name of the buffer variable.
&buffer == the pointer to the UInt8 array object named buffer.