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

后端 未结 1 1467
借酒劲吻你
借酒劲吻你 2021-02-04 16:11

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

相关标签:
1条回答
  • 2021-02-04 16:30

    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()
    
    0 讨论(0)
提交回复
热议问题