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

当我使用NSOutputStreamwrite方法时

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

我不知道如何转换StringUnsafePointer<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()

方法。


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

以上是 如何将字符串转换为UnsafePointer 和长度 的全部内容, 来源链接: utcz.com/qa/406345.html

回到顶部