swift是否有写入字节流的协议?

san*_*anz 7 io outputstream swift

我在Swift书中找不到关于io的任何内容.是否有类似于Java的OutputStream或Go的Writer接口的通用协议用于写入字节流?如果您正在编写一个返回流的类,您是否需要编写自己的协议或使用Objective C协议?

要明确我要求Swift原生接口不是因为我避免使用Objective C或Cocoa,而是为了描述Swift到Swift代码的预期行为.

Jos*_*ark 13

这是Swift文档很安静的东西,我想知道更多,所以我调查了它.

有一个协议,它被称为Streamable:

protocol Streamable {
    func writeTo<Target : OutputStream>(inout target: Target)
}
Run Code Online (Sandbox Code Playgroud)

OutputStream:

protocol OutputStream {
    func write(string: String)
}
Run Code Online (Sandbox Code Playgroud)

write 允许写入对象.

String 符合两者,便于写入和写入:

var target = String()
"this is a message".writeTo(&target)
println(target)
// this is a message
Run Code Online (Sandbox Code Playgroud)

写入文件:

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
Run Code Online (Sandbox Code Playgroud)

还有writeToUrl.

我假设这些函数都是基于Cocoa流构建的,它们具有类似的功能:

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()
Run Code Online (Sandbox Code Playgroud)