小编典典

如何将字符串转换为UnsafePointer 和长度

swift

当我使用NSOutputStreamwrite方法时

func write(_ buffer: UnsafePointer<UInt8>, maxLength length: Int) -> Int

我不知道如何转换StringUnsafePointer<UInt8>和长度

如何迅速做到这一点?


阅读 415

收藏
2020-07-07

共1个答案

小编典典

您必须先将字符串转换为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()
方法。


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) }
2020-07-07