当我使用NSOutputStream的write方法时
NSOutputStream
write
func write(_ buffer: UnsafePointer<UInt8>, maxLength length: Int) -> Int
我不知道如何转换String 为UnsafePointer<UInt8>和长度
String
UnsafePointer<UInt8>
如何迅速做到这一点?
您必须先将字符串转换为UTF-8数据
let string = "foo bar" let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
然后将其写入输出流
let outputStream: NSOutputStream = ... // the stream that you want to write to let bytesWritten = outputStream.write(UnsafePointer(data.bytes), maxLength: data.length)
该UnsafePointer()转换是必要的,因为data.bytes有型UnsafePointer<Void>,而不是UnsafePointer<UInt8>如预期的write() 方法。
UnsafePointer()
data.bytes
UnsafePointer<Void>
write()
Swift 3更新:
let string = "foo bar" // Conversion to UTF-8 data (cannot fail): let data = string.data(using: String.Encoding.utf8)! // Write to output stream: let outputStream: NSOutputStream = ... // the stream that you want to write to let bytesWritten = data.withUnsafeBytes { outputStream.write($0, maxLength: data.count) }