I am trying to write a generic function that will read an int-typed value from NSInputStream
:
func read() -> T? {
var
The read()
method requires a mutable buffer pointer:
let n = withUnsafeMutablePointer(&buffer) { (p) in
self.read(UnsafeMutablePointer(p), maxLength: sizeof(T))
}
The placeholder type
in UnsafeMutablePointer(p)
can be inferred automatically from the context.
Note that there is a general problem with your approach: If the input
stream is not connected to a real file but to some communication channel
(e.g. a TCP socket, pipe, ...) then the only guarantee is that read()
waits until at least one byte is read and the assertion n == sizeof(T)
can fail. You have to read again in a loop until the required amount
is read.