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

邮差的信 提交于 2019-12-03 01:30:01

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!