Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does swift have a protocol for writing a stream of bytes?

I can't find anything in the Swift book about io. Is there any generic protocol similar to Java's OutputStream or Go's Writer interface for writing a stream of bytes? If you are writing a class that returns a stream, do you need to write your own protocol or use an Objective C protocol?

To be clear am asking for a Swift native interface for this not because I avoiding using Objective C or Cocoa, but for a description of the expected behavior for Swift to Swift code going forward.

like image 289
sanz Avatar asked Jun 12 '14 12:06

sanz


1 Answers

This is something the Swift docs are quiet about and I wanted to know more about so I looked into it.

There is a protocol, it's called Streamable:

protocol Streamable {
    func writeTo<Target : OutputStream>(inout target: Target)
}

OutputStream:

protocol OutputStream {
    func write(string: String)
}

write allows an object to be written to.

String conforms to both, making it easy to write to and from:

var target = String()
"this is a message".writeTo(&target)
println(target)
// this is a message

Writing to a file:

var msg = "this will be written to an output file"
msg.writeToFile("output.txt", atomically: false, encoding: NSUTF8StringEncoding, error: nil)
// creates 'output.txt' in the same folder as the executable

There is also writeToUrl.

I assume those functions are all built on top of Cocoa streams, which have similar functionality:

var os = NSOutputStream(toFileAtPath: "output.txt", append: true)
os.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)

var msg = "a truly remarkable message"
var ptr:CConstPointer<UInt8> = msg.nulTerminatedUTF8

os.open()
os.write(ptr, maxLength: msg.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
os.close()
like image 193
Joseph Mark Avatar answered Nov 01 '22 06:11

Joseph Mark