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

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

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

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

一个协议,它叫做Streamable:

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

的OutputStream:

protocol OutputStream {
    func write(string: String)
}

write允许写入对象.

String符合两者,使得写入和从中都很容易:

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

写入文件

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

还有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()

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...